Introduction
In this lab, we will explore the findFirstN() function in JavaScript. This function is used to find the first n elements in an array for which a given function returns a truthy value. We will learn how to use findFirstN() in combination with other array methods to manipulate and extract specific data from arrays.
How to Find the First N Matches
To find the first n elements that meet a certain criteria, use the findFirstN function. Here's how:
- Open the Terminal/SSH.
- Type
nodeto start practicing coding. - Use the
findFirstNfunction, passing in the array to search through, a matching function, and the number of matches to find (if not specified, the default is 1). - The
matcherfunction will be executed for each element of thearr, and if it returns a truthy value, that element will be added to the results array. - If the
resarray reaches a length ofn, the function will return the results array. - If no matches are found, an empty array will be returned.
Here's the code for the findFirstN function:
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;
};
And here are some examples of how to use it:
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]
Summary
Congratulations! You have completed the Find First N Matches lab. You can practice more labs in LabEx to improve your skills.