Array find() and findIndex()
The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
If you need the index of the found element in the array, use findIndex().
If you need to find the index of a value, use indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
If you need to find if a value exists in an array, use includes(). Again, it checks each element for equality with the value instead of using a testing function.
If you need to find if any element satisfies the provided testing function, use some().
If you need to find all elements that satisfy the provided testing function, use filter().
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 45 | 12 | 25 | 8 | 45 | 8 | |
| Built-in object | ||||||
| The findIndex() method of Array instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. | 45 | 12 | 25 | 8 | 45 | 8 |
| The find() method of TypedArray instances returns the first element in the provided typed array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. This method has the same algorithm as Array.prototype.find(). | 45 | 12 | 37 | 10 | 45 | 10 |
| The findIndex() method of TypedArray instances returns the index of the first element in a typed array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method has the same algorithm as Array.prototype.findIndex(). | 45 | 12 | 37 | 10 | 45 | 10 |
Syntax
const users = [
{ name: 'Taro', age: 25 },
{ name: 'Hanako', age: 30 },
{ name: 'Jiro', age: 25 },
];
users.find(u => u.age === 25); // { name: 'Taro', age: 25 }
users.findLast(u => u.age === 25); // { name: 'Jiro', age: 25 }
users.findIndex(u => u.age === 30); // 1 Live demo
Use cases
-
Finding the first match
Pick the first user, product, or route that satisfies a predicate without manual loop bookkeeping.
-
Finding the latest match
Use findLast when recent history matters, such as the most recent warning or last matching navigation item.
Cautions
- find returns undefined when nothing matches, so do not assume a value always exists.
- If you need many matches, filter is usually the better API because it makes the output shape explicit.
Accessibility
- When a found item becomes selected or focused in the UI, reflect that change visibly instead of relying on code state alone.