Introducing `findLast` and `findLastIndex`

Laurie - Jun 16 '21 - - Dev Community

I'm back with another introduction to JavaScript syntax! Currently in Stage 2, we're going to talk about findLast and findLastIndex.

Array.prototype.find

Let's start by talking about a sometimes used array function called find. It's a nice utility method that helps you find the first element in an array that meets the given criteria.

const arr = [
  { letter: 'a', integer: 1 },
  { letter: 'c', integer: 2 },
  { letter: 'c', integer: 3 },
  { letter: 'd', integer: 4 },
]
arr.find(el => el.letter === 'c') // { letter: 'c', integer: 2 },
Enter fullscreen mode Exit fullscreen mode

There is a complimentary function called findIndex.

const arr = [
  { letter: 'a', integer: 1 },
  { letter: 'c', integer: 2 },
  { letter: 'c', integer: 3 },
  { letter: 'd', integer: 4 },
]
arr.findIndex(el => el.letter === 'c') // 1
Enter fullscreen mode Exit fullscreen mode

You can imagine why someone might want to do this. If you're looking for an element that matches what you want, but you only need one, this is super useful and very performant.

But it's only first

While find is great, it always gets the first element that meets the criteria. What happens if you're continuously pushing elements onto your array and you want the "most recent" element that meets the criteria. This would be the element closest to the end.

You could do this in a few ways. The one that comes to mind for me is to reverse the array and then use find. But this isn't performant for large arrays, it requires more steps than it should, and it doesn't work well if there aren't any matching elements in the array.

Enter findLast. It's the mirror function to find, but it works from the end of the array.

const arr = [
  { letter: 'a', integer: 1 },
  { letter: 'c', integer: 2 },
  { letter: 'c', integer: 3 },
  { letter: 'd', integer: 4 },
]
arr.findLast(el => el.letter === 'c') // { key: 'c', integer: 3 }
Enter fullscreen mode Exit fullscreen mode

There is also a matching findLastIndex.

const arr = [
  { letter: 'a', integer: 1 },
  { letter: 'c', integer: 2 },
  { letter: 'c', integer: 3 },
  { letter: 'd', integer: 4 },
]
arr.findLastIndex(el => el.letter === 'c') // 2
Enter fullscreen mode Exit fullscreen mode

Note that if it can't find an element that matches the criteria, it will return -1.

What do you think?

In my mind we can never have too many array utility methods! Whether I need them or not. But how about you?

If you're interested in learning more, check out the proposal.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .