Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.findIndex

Returns the index of the first element that passes a test.

Available since: ES2015

Syntax

array.findIndex(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA 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:

2

Updating 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

Related recipes

In the tutorial

  • Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.

Thanks for reading!

Donate to the site — we work hard for you.