.findLast()
and .findLastIndex()
This blog post describes the ECMAScript proposal “Array find from last” by Wenlu Wang and Daniel Rosenwasser.
In this blog post, we explore methods of Arrays. But everything we learn also applies to Typed Arrays.
The following three methods search Arrays from start to end:
> ['a', 'b', 'a'].indexOf('a')
0
> ['a', 'b', 'a'].indexOf('c')
-1
> ['a1', 'b', 'a2'].find(x => x.startsWith('a'))
'a1'
> ['a1', 'b', 'a2'].find(x => x.startsWith('c'))
undefined
> ['a1', 'b', 'a2'].findIndex(x => x.startsWith('a'))
0
> ['a1', 'b', 'a2'].findIndex(x => x.startsWith('c'))
-1
So far, only .indexOf()
has a version that searches from end to start:
> ['a', 'b', 'a'].lastIndexOf('a')
2
The proposal introduces such versions for .find()
and .findIndex()
:
> ['a1', 'b', 'a2'].findLast(x => x.startsWith('a'))
'a2'
> ['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a'))
2
The following code shows simple implementations (fewer checks than the actual implementations) of .findLast()
and .findLastIndex()
:
function findLast(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return value;
}
}
return undefined;
}
function findLastIndex(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return index;
}
}
return -1;
}
The proposal mentions 2 polyfills that are currently available.
Additionally libraries such as Lodash and Ramda also provide the operations findLast
and findLastIndex
for Arrays.
.find()
, .findIndex()
” in “JavaScript for impatient programmers”