Introduction
In this lab, we will explore the concept of finding the last n elements that satisfy a given condition in an array. We will learn how to use a for loop to iterate through the array and execute a provided function on each element. We will also learn how to use the Array.prototype.unshift() method to prepend matching elements to the results array and return it once the desired length is reached.
Instructions to find Last N Matches
To find the last n elements that match a certain condition, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
findLastNfunction provided below. - Provide an array
arrand amatcherfunction that returns a truthy value for the elements you want to match. - Optionally, you can also provide the number
nof matches you want to return (default is 1). - The function will execute the
matcherfunction for each element ofarrusing aforloop, starting from the last element. - If an element matches the
matchercondition, it will be added to the results array usingArray.prototype.unshift(), which prepends elements to the array. - When the length of the results array is equal to
n, the function will return the results. - If there are no matches or
nis greater than the number of matches, an empty array will be returned.
const findLastN = (arr, matcher, n = 1) => {
let res = [];
for (let i = arr.length - 1; i >= 0; i--) {
const el = arr[i];
const match = matcher(el, i, arr);
if (match) res.unshift(el);
if (res.length === n) return res;
}
return res;
};
Here are some examples of how to use the findLastN function:
findLastN([1, 2, 4, 6], (n) => n % 2 === 0, 2); // [4, 6]
findLastN([1, 2, 4, 6], (n) => n % 2 === 0, 5); // [2, 4, 6]
Summary
Congratulations! You have completed the Find Last N Matches lab. You can practice more labs in LabEx to improve your skills.