Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

Maria

The 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
-1

From the end

findLast() searches from the end of the array:

const numbers = [5, 12, 8, 130];
 
console.log(numbers.findLast((n) => n < 100));

Output:

8

All 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, Maria

Common 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 found

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.