search
Array.prototype.findIndex
Returns the index of the first element for which the callback returns truthy, or -1 if none match. Reach for it when you need the position — e.g. to splice or replace.
arr.findIndex(callbackFn[, thisArg]) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(element, index, array) | Predicate; first truthy element's index is returned |
| thisArg | Value used as `this` inside callbackFn |
Examples
console.log([1,2,3,4].findIndex(n => n > 2)); Logs: 2
console.log([1,2,3].findIndex(n => n > 99)); Logs: -1
const arr = [{id:'a'},{id:'b'}]; const i = arr.findIndex(o => o.id === 'b'); arr.splice(i, 1); console.log(arr); Logs: [{id: 'a'}]
console.log([NaN, 1, 2].findIndex(v => Number.isNaN(v))); Logs: 0 (works for NaN unlike indexOf)
Gotcha
Returns -1 when nothing matches (falsy!). Use it instead of indexOf when you need custom equality or want to match NaN.
Related methods
Array.prototype.find
Returns the first element for which the callback returns truthy, or undefined if none match. Reach for it when you need the matching item itself, not just its index.
Array.prototype.findLast
Walks the array from the END and returns the last element for which the callback returns truthy (ES2023). Reach for it when the most recent matching entry is what you want.
Array.prototype.indexOf
Returns the first index where searchElement is strictly equal (===) to an array item, or -1. Reach for it for a fast, exact primitive lookup — but not for objects or NaN.
Array.prototype.includes
Returns true if the array contains searchElement using SameValueZero equality (ES2016). Reach for it as the readable boolean alternative to `indexOf(x) !== -1`.