Array Find & FindIndex Methods
find() returns the first element for which the callback returns a truthy value, and stops searching there. If no element passes, it returns undefined. It is the usual way to look up one record in an array of objects.
const users = [ { id: 101, name: 'Asha', role: 'admin' }, { id: 102, name: 'Tom', role: 'editor' }, { id: 103, name: 'Mei', role: 'editor' },];
console.log(users.find((user) => user.role === 'editor'));console.log(users.find((user) => user.id === 999));This prints:
{ id: 102, name: 'Tom', role: 'editor' }undefinedOnly Tom is returned, although Mei is an editor too. To get every match, use filter().
findIndex
Section titled “findIndex”findIndex() runs the same search but returns the position of the first match, or -1 if there is none. Use it when you need to change or remove the element in the array, rather than just read it.
const todos = ['Water the plants', 'Pay the gas bill', 'Return library books'];
const index = todos.findIndex((todo) => todo.startsWith('Pay'));console.log(index);
todos[index] = 'Pay the gas bill (done)';console.log(todos);
console.log(todos.findIndex((todo) => todo.startsWith('Call')));This prints:
1[ 'Water the plants', 'Pay the gas bill (done)', 'Return library books']-1Check for -1 before using the index, because todos[-1] would silently create a property called -1 instead of changing an element. findIndex() is also the safer test when the array might hold undefined, because find() returns undefined both for a match on that value and for no match at all.
Searching from the end
Section titled “Searching from the end”findLast() and findLastIndex(), added in ES2023, search from the last element backwards and return the last match instead of the first.
const temperatures = [14, 22, 17, 24, 19];
console.log(temperatures.find((t) => t > 20));console.log(temperatures.findLast((t) => t > 20));console.log(temperatures.findLastIndex((t) => t > 20));This prints:
22243Passing a value for this
Section titled “Passing a value for this”Like most array methods that take a callback, find() and findIndex() accept a second argument that becomes this inside the callback. It works only with a regular function, because an arrow function takes this from the code around it and ignores the argument.
const products = ['mug', 'teapot', 'cafetière', 'teaspoon'];const search = { prefix: 'tea' };
const match = products.find(function (product) { return product.startsWith(this.prefix);}, search);
console.log(match);This prints:
teapotIn modern code an arrow function that reads search.prefix directly is simpler and does the same job, so this argument is rarely needed.
Steve Griffith covers this topic in his video Array find( ) and findIndex( ) Methods.