JavaScript Reference ยท Array
JavaScript Array findIndex() method
Reference for JavaScript Array findIndex(): get the index of the first element that passes a test, or -1, with callback arguments and common patterns.
The findIndex() method returns the index of the first element for which your callback returns a truthy value, or -1 if no element passes. Like find(), it stops at the first match.
It is the right choice when you need to know where something is, for example to replace or remove it, or when the array might contain undefined and a plain find() result would be ambiguous.
["a", "b", "c"].findIndex((x) => x === "b"); // 1
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
findIndex(callbackFn) findIndex(callbackFn, thisArg)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(element, index, array). Return a truthy value for the element you are looking for. |
thisArg |
Optional. Value used as this inside callbackFn (ignored by arrow functions). |
Return value: the index (a number from 0) of the first element that passed, or -1 if none did.
Exceptions: a TypeError if callbackFn is not a function.
Usage notes
- Check for
-1before using the index. The second example shows why:splice(-1, 1)does not do nothing, it removes the last element. - Truthiness is enough. The callback result does not have to be exactly
true. - Reliable with
undefined. An element equal toundefinedis found at its real index, unlikefind(), which would returnundefinedeither way. - Holes are visited as
undefined, unlikeindexOf()andsome(), which skip them. - Value or condition?
indexOf(value)uses strict equality for a plain value.findIndex()is for conditions, and the only choice for objects matched by a property or forNaN(arr.findIndex(Number.isNaN)). - From the end:
findLastIndex()searches from the last element. - Immutable updates: pair it with
with()or spread to replace an element without mutating:arr.with(i, newValue).
Browser support
findIndex() is supported in every current browser.