JavaScript Reference ยท Array
JavaScript Array findLastIndex() method
Reference for JavaScript Array findLastIndex(): get the index of the last element that passes a test by searching backward, or -1 when nothing matches.
The findLastIndex() method searches an array from the end toward the start and returns the index of the first element it meets that makes your callback return a truthy value. In array order, that is the last matching element. If nothing matches, it returns -1.
It is the backward version of findIndex() and the condition-based cousin of lastIndexOf().
[1, 4, 6, 3].findLastIndex((n) => n % 2 === 0); // 2
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
findLastIndex(callbackFn) findLastIndex(callbackFn, thisArg)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(element, index, array). Return a truthy value for the element you want. |
thisArg |
Optional. Value used as this inside callbackFn (ignored by arrow functions). |
Return value: the index of the last element that passed, or -1 if none did.
Exceptions: a TypeError if callbackFn is not a function.
Usage notes
- Visited in reverse. The callback runs for indexes
length - 1down to0and the search ends at the first pass. The index you receive and return is always the real position in the array. - Check for
-1. As withfindIndex(), test the result before using it as an index.splice(-1, 1), for example, removes the last element instead of doing nothing. - Good for "everything up to the last X". Combine it with
slice()to cut trailing items that do not matter, as in the second example. - Holes are visited as
undefined. - Unambiguous. It distinguishes "found an
undefinedelement" from "not found", whichfindLast()cannot. - Plain values: use
lastIndexOf(value)for strict-equality searches. - Mutation: it never changes the array.
Browser support
findLastIndex() arrived together with findLast(). It works in current browsers, but check a compatibility table if you must support older ones.