Array.prototype.findIndex
Returns the index of the first element that passes a test.
Available since: ES2015
Syntax
array.findIndex(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A test function: receives the element, its index and the array, and returns true for a match. |
Return value
numberThe index of the first matching element, or -1.
Examples
The index of the first negative number:
console.log([4, 7, -2, 9].findIndex((n) => n < 0));Output:
2Updating an object in an array by id:
const users = [{ id: 1, name: 'Anna' }, { id: 2, name: 'Oleg' }];
const index = users.findIndex((user) => user.id === 2);
users[index] = { ...users[index], name: 'Oleg P.' };
console.log(users[1].name);Output:
Oleg P.Notes
If nothing is found the result is -1. Check it: users[-1] returns undefined, not an error.
See also
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.indexOf — Finds a value in an array and returns its index.
- Array.prototype.findLastIndex — Returns the index of the last element that passes a test.
Related recipes
In the tutorial
- Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.