ECMAScript question detail
Find array from last
This release introduced two new array methods named findLast() and findLastIndex() to search an array element from the last. Their functionality is similar to find() and findIndex() but searching starts from the end of an array. These methods are available on Array and TypedArray prototypes. This feature provides an efficient way for reverse order search by eliminating the process of manual array reversal.
For example, let's see the usage of finding odd elements from end of an array prior to ES2023. There are no direct methods available to search element from end of an array. Hence, the array needs to be reversed first before applying first() and firstIndex() methods.
const isOdd = (number) => number % 2 === 1;
const numbers = [1, 2, 3, 4, 5];
const reverseNumbers = [5, 4, 3, 2, 1];
console.log(reverseNumbers.find(isOdd)); // 5
console.log(reverseNumbers.findIndex(isOdd)); // 4
This process is going to be simplified in ES2023 release using findLast() and findLastIndex() methods.
const isOdd = (number) => number % 2 === 1;
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.findLast(isOdd)); // 5
console.log(numbers.findLastIndex(isOdd)); // 4