ECMAScript proposal: searching Arrays from end to start via .findLast() and .findLastIndex()

[2022-03-24] dev, javascript, es proposal
(Ad, please don’t block)

This blog post describes the ECMAScript proposal “Array find from last” by Wenlu Wang and Daniel Rosenwasser.

Topic of this blog post: methods of Arrays and of Typed Arrays  

In this blog post, we explore methods of Arrays. But everything we learn also applies to Typed Arrays.

Searching 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

Simple implementations  

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;
}

Availability  

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.

Further reading