Find the Last Matching Array Element with `findLast()`
1
min read .
Updated on
Array.prototype.findLast() searches an array from the end and returns the first element, in reverse order, that satisfies a predicate.
const numbers = [1, 3, 5, 8, 10, 12, 7, 6];
const lastEven = numbers.findLast((number) => number % 2 === 0);
console.log(lastEven); // 6
For objects:
const transactions = [
{ id: 1, amount: 100 },
{ id: 2, amount: 200 },
{ id: 3, amount: 300 },
{ id: 4, amount: 150 },
{ id: 5, amount: 250 },
];
const lastLarge = transactions.findLast((tx) => tx.amount > 200);
console.log(lastLarge); // { id: 5, amount: 250 }
If nothing matches, the method returns undefined.
Unlike array.toReversed().find(...), findLast() does not need to create a reversed copy just to search from the end.
Conclusion
Use findLast() for “most recent matching item” queries on arrays ordered from oldest to newest. Use findLastIndex() instead when you need the position rather than the element itself.