Find IndexLoading saved progress…

Find Index

Implement findIndex(array, predicate, [fromIndex=0]) — scan an array from left to right and return the index of the first element for which predicate returns a truthy value. If no element matches, return -1. This is the same contract as the built-in Array.prototype.findIndex and Lodash's _.findIndex: the difference from a plain search is that you decide what "match" means by passing a test function instead of a fixed value.

Signature

// array:     T[]                                  — the array to scan.
// predicate: (value: T, index: number, array: T[]) => unknown
//   Called on each element; the first element whose call returns a
//   truthy value is the match. Receives the value, its index, and the
//   whole array.
// fromIndex: number = 0                            — index to start scanning from.
// returns:   number   — the index of the first match, or -1 if none match.
function findIndex(array, predicate, fromIndex = 0): number;

Examples

// First element greater than 5 is 6, at index 1.
findIndex([4, 6, 8], (n) => n > 5);
// → 1
// No element is greater than 9, so there is no match.
findIndex([1, 2, 3], (n) => n > 9);
// → -1
// Start scanning at index 2, so the earlier 2 at index 1 is skipped;
// the next match is the 2 at index 3.
findIndex([1, 2, 1, 2], (n) => n === 2, 2);
// → 3

Notes

  • First match wins. Return as soon as the predicate is truthy; never keep scanning for a "better" later match.
  • The predicate gets three arguments. It receives (value, index, array), so a test can depend on the position, not just the value.
  • Truthy, not true. A predicate that returns 'hit', 42, or any non-falsy value counts as a match — you are testing for truthiness, not strict equality with true.
  • fromIndex defaults to 0. When omitted, the scan begins at the first element. A fromIndex past the end means nothing is scanned, so the result is -1.
  • Empty in, -1 out. findIndex([], fn) returns -1 because there is nothing to test.
  • Don't mutate the input. Read each element; return a number. Negative fromIndex (counting from the end) is out of scope here — see Going further.
Loading editor…