Published on

Finding Last Array Match with Array.findLast() in JavaScript

Authors

When we use the find() method in an array, it searches for the item from first to last. If the criteria match, it returns the value and skips the rest. If it does not find anything, then undefined is returned.

However, if you want to search from last to first instead, you can use the findLast() method.

const isEven = (number) => number % 2 === 0;

const numbers = [1, 2, 3, 4];

// Find the first even number in the array using the isEven function
const firstEvenNumber = numbers.find(isEven); // returns 2

// Find the last even number in the array using the isEven function
const lastEvenNumber = numbers.findLast(isEven); // returns 4

You can also use the findLastIndex() method to get the index in the array.

const isEven = (number) => number % 2 === 0;

const numbers = [1, 2, 3, 4];

// Find the last even number in the array using the isEven function
const lastEvenNumberIndex = numbers.findLastIndex(isEven); // returns 3

Note

Both .findLast() and .findLastIndex() methods are recently merged proposals (as of 2023) and may not be supported in older browsers or runtime environments.

Reference

Happy element searching!