Find Last IndexLoading saved progress…

Find Last Index

Implement findLastIndex(array, predicate, [fromIndex]) — return the index of the last element for which predicate returns a truthy value, scanning backward from the end of the array. If nothing matches, return -1. This mirrors Lodash's _.findLastIndex and is the right-to-left twin of the built-in Array.prototype.findIndex, which scans left to right.

Signature

// array:     T[]                              — the array to search.
// predicate: (value: T, index: number, array: T[]) => boolean
//            — called on each element; the search stops at the first truthy result.
// fromIndex: number = array.length - 1
//            — the index the BACKWARD scan starts from (inclusive). Defaults
//              to the last index, so the whole array is searched by default.
// returns:   number  — the index of the last matching element, or -1.
function findLastIndex(array, predicate, fromIndex): number;

Examples

// Several elements are odd (1 and 3); the LAST odd one is the 3 at index 2.
findLastIndex([1, 2, 3, 4], (n) => n % 2 === 1);
// → 2

// No element is odd, so there is no match.
findLastIndex([2, 4, 6], (n) => n % 2 === 1);
// → -1
// fromIndex = 1 starts the backward scan at index 1, so the 1 at index 2 is
// never seen; only the 1 at index 0 is reachable.
findLastIndex([1, 2, 1, 2], (n) => n === 1, 1);
// → 0

Notes

  • Scan from the end. When more than one element matches, you must return the index closest to the end, not the first one a left-to-right scan would hit.
  • The predicate gets three arguments. It receives (value, index, array), the same shape as Array.prototype.findIndex. Most predicates only use value, but index and array must still be passed.
  • fromIndex is where the backward scan begins, inclusive. Elements at indexes greater than fromIndex are out of range and never tested.
  • fromIndex defaults to the last index (array.length - 1), so calling without it searches the whole array.
  • No match returns -1, and an empty array always returns -1.
  • Don't mutate the input. You only need to read each element; build nothing.
Loading editor…