JavaScript proposal array find from last
At the moment of this writing two brand-new array methods named findLast
and findLastIndex
are getting closer to official release since they are in stage 3.
JavaScript currently supports Array.prototype.indexOf() and Array.prototype.lastIndexOf() to find the index of an item in the array.
Apart from these, we can use Array.prototype.find() and Array.prototype.findIndex() to spot an element in the array based on some condition. These two methods search starting from the left side and they stop when they find a match.
So obviously there is no way to search for an array item using a condition starting from the right side of the array and this is what these two new methods are bringing to the table.
Let's see an example:
const array = [
{name: 'John', age: 15},
{name: 'Jane', age: 21},
{name: 'Jack', age: 12},
];
const lastKid = array.findLast((el, index, array) => {
return el.age < 18;
});
console.log(lastKid);
// {name: 'Jack', age: 12}
const lastKidIndex = array.findLastIndex((el, index, array) => {
return el.age < 18;
});
console.log(lastKidIndex);
// 2
Before these methods we were used to combining Array.prototype.reverse()
and Array.prototype.find()
to achieve the same result but this pattern was introducing an unnecessary mutation or copy of the original array as we can see below:
// This is error-prone since it mutates the original array
const lastKid = array.reverse().find((el, index, array) => {
return el.age < 18;
});
// This creates an unnecessary copy of the original array
// just to avoid the mutation
const lastKid = [...array].reverse().find((el, index, array) => {
return el.age < 18;
});
That said, there is no need to do such things now with findLast
and findLastIndex
methods.
Here is a Codesandbox you can use to play with these two pretty helpful methods straight ahead.
Notice the imported modules core-js/actual/array/find-last
and core-js/actual/array/find-last-index
I had to pull from core-js to make them work. Cheers!!
Did you like this one?
I hope you really did...
Newsletter
Get notified about latest posts and updates once a week!!
You liked it?