Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Find the Last Matching Array Index with `findLastIndex()`

1 min read .
Find the Last Matching Array Index with `findLastIndex()`

Array.prototype.findLastIndex() searches from the end of an array and returns the index of the first element, in reverse order, that matches a predicate.

const numbers = [1, 3, 5, 8, 10, 12, 7, 6];
const index = numbers.findLastIndex((number) => number % 2 === 0);

console.log(index); // 7

For object arrays:

const transactions = [
  { id: 1, amount: 100 },
  { id: 2, amount: 200 },
  { id: 3, amount: 300 },
  { id: 4, amount: 150 },
  { id: 5, amount: 250 },
];

const index = transactions.findLastIndex((tx) => tx.amount > 200);
console.log(index); // 4

If no element matches, the result is -1.

Use findLast() when you need the matching value itself and findLastIndex() when you need its position for a later update, removal, or lookup.

Conclusion

findLastIndex() is the direct way to find the position of the last element matching a condition without reversing the array or writing a manual backward loop.

Related Posts

chevron-up