JavaScriptArrays

Array.prototype.findLastIndex()

Returns the index of the last element matching a condition, searching from the end, or -1.

Returns
The index of the last matching element, or -1.
Changes the original
No
On this page

Example

#
JavaScript
const lessons = [
  { title: 'Variables', done: true },
  { title: 'Loops', done: true },
  { title: 'Functions', done: false },
  { title: 'Arrays', done: false }
]

console.log(lessons.findLastIndex((lesson) => lesson.done))
console.log(lessons.findIndex((lesson) => !lesson.done))
console.log(lessons.findLastIndex((lesson) => lesson.title === 'Classes'))
Console
1
2
-1

Definition and usage

#

The findLastIndex() method checks elements with a testing function, starting from the end of the array. It returns the index of the first match it finds, which is the last matching element in the array’s order. When no element meets the condition, the result is -1.

It’s the backward-searching counterpart to findIndex(). It’s handy for chronological data when you care about the most recent entry: the last completed lesson, the last failed login attempt, or the last message from a mentor.

The index lets you not just read the element, but also replace it, remove it with splice(), or cut out a chunk of the array with slice(). If you only need the element itself, findLast() is simpler.

Syntax

#
Syntax
array.findLastIndex(callbackFn)
array.findLastIndex(callbackFn, thisArg)

Parameters

#
  • callbackFn

    function (element, index, array)

    The testing function, called from the last element toward the first.
  • thisArg

    optional

    The this value inside the function.

More examples

#
Everything after the last error
JavaScript
const log = ['ok', 'error', 'ok', 'error', 'ok', 'ok']
const lastError = log.findLastIndex((entry) => entry === 'error')

console.log(lastError)
console.log(log.slice(lastError + 1))
Console
3
['ok', 'ok']

When the log has no error at all, findLastIndex() returns -1, and slice(0) returns the whole array. Here, that happens to be the result we want.

Flagging the most recent weak attempt
JavaScript
const attempts = [
  { id: 1, score: 40 },
  { id: 2, score: 85 },
  { id: 3, score: 55 }
]

const index = attempts.findLastIndex((attempt) => attempt.score < 60)
if (index !== -1) {
  attempts[index] = { ...attempts[index], retry: true }
}

console.log(index)
console.log(attempts[index])
Console
2
{ id: 3, score: 55, retry: true }

Browser support

#

Widely available · since 2022

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Check for -1 before using the index. Assigning to array[-1] won’t change any element; it just adds a strange property named "-1" to the array.
  • For simple values, lastIndexOf() is enough. findLastIndex() is needed when you’re searching by a condition, such as an object’s field.

Related entries

#

Spotted a mistake or missing an example? Write to us.