Proposal for the .findLast()
and .findLastIndex()
methods on array and typed array.
Motivation
Finding an element in an array is a very common programming pattern.
It can improve performance by avoiding obvious overhead and improve the constant factors in the time complexity. It can be useful in some performance-sensitive scenarios. eg: React render function.
Core Feature
Adds Array.prototype.findLast
and Array.prototype.findLastIndex
.
This would behave the same as Array.prototype.find and Array.prototype.findIndex but would iterate from the last to the first.
Code examples
const array = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]; array.find(n => n.value % 2 === 1); // { value: 1 } array.findIndex(n => n.value % 2 === 1); // 0 // ======== Before the proposal =========== // find [...array].reverse().find(n => n.value % 2 === 1); // { value: 3 } // findIndex array.length - 1 - [...array].reverse().findIndex(n => n.value % 2 === 1); // 2 array.length - 1 - [...array].reverse().findIndex(n => n.value === 42); // should be -1, but 4 // ======== In the proposal =========== // find array.findLast(n => n.value % 2 === 1); // { value: 3 } // findIndex array.findLastIndex(n => n.value % 2 === 1); // 2 array.findLastIndex(n => n.value === 42); // -1
Polyfills
https://github.com/zloirock/core-js#array-find-from-last
Top comments (0)