Array find() and findIndex()
find() and findIndex() search from the start of an array, while findLast() and findLastIndex() search from the end. They make intent clearer than building manual loops for common lookups.
Overview
find() and findIndex() search from the start of an array, while findLast() and findLastIndex() search from the end. They make intent clearer than building manual loops for common lookups.
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.
Related links
Powered by web-features