How to find an element in an array by a condition
Short answer
find() returns the first element for which the function returns true:
const users = [
{ id: 1, name: 'Anna', age: 30 },
{ id: 2, name: 'Oleg', age: 17 },
{ id: 3, name: 'Maria', age: 25 },
];
console.log(users.find((user) => user.id === 3).name);Output:
MariaThe position
findIndex() returns the index of the element, or -1:
const numbers = [5, 12, 8, 130];
console.log(numbers.findIndex((n) => n > 10));
console.log(numbers.findIndex((n) => n > 1000));Output:
1
-1From the end
findLast() searches from the end of the array:
const numbers = [5, 12, 8, 130];
console.log(numbers.findLast((n) => n < 100));Output:
8All matches
find() stops at the first match. To get all of them, use filter():
const users = [
{ name: 'Anna', age: 30 },
{ name: 'Oleg', age: 17 },
{ name: 'Maria', age: 25 },
];
console.log(users.filter((user) => user.age >= 18).map((user) => user.name).join(', '));Output:
Anna, MariaCommon mistake
If nothing is found, find() returns undefined, and reading a property from it throws an error. Use ?.:
const users = [{ id: 1, name: 'Anna' }];
const user = users.find((u) => u.id === 5);
console.log(user?.name ?? 'not found');Output:
not foundFunctions used in this recipe
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.findIndex — Returns the index of the first element that passes a test.
- Array.prototype.findLast — Searches from the end of an array for the first element that passes a test.
- Array.prototype.filter — Creates a new array from the elements that pass a test.