853 B
853 B
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Find first n matches | array | intermediate | blog_images/digital-nomad-5.jpg | 2021-05-09T13:31:36+03:00 | 2021-05-09T13:31:36+03:00 |
Finds the first n elements for which the provided function returns a truthy value.
- Use a
for...inloop to execute the providedmatcherfor each element ofarr. - Use
Array.prototype.push()to append elements to the results array and return them if itslengthis equal ton.
const findFirstN = (arr, matcher, n = 1) => {
let res = [];
for (let i in arr) {
const el = arr[i];
const match = matcher(el, i, arr);
if (match) res.push(el);
if (res.length === n) return res;
}
return res;
};
findFirstN([1, 2, 4, 6], n => n % 2 === 0, 2); // [2, 4]
findFirstN([1, 2, 4, 6], n => n % 2 === 0, 5); // [2, 4, 6]