Finding elements in arrays

Check if an element exists in an array

Use the includes array method to tell if an element exists in the array.

const array = [2, 3, 4, 5, 6];
array.includes(3); // true

array.includes(12); // false

Alternatively, you can also use the indexOf array method to check if the value is greater than -1.

const array = [2, 3, 4, 5, 6];
array.indexOf(3) > -1; // true

array.indexOf(12) > -1; // false

Find element in an array

Use the find method on the array to find the element. The parameter passed to the find method defines the condition for finding the element.

If you need the index of the element, use findIndex instead of find.

let selector = 4;
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Find `4` in array
array.find((element) => element === selector); // 4
array.findIndex((element) => element === selector); // 3

selector = 12;
// Find `12` in array
array.find((element) => element === selector); // undefined
array.findIndex((element) => element === selector); // -1

// Find even number in array
array.find((element) => element % 2 === 0); // 2
array.findIndex((element) => element % 2 === 0); // 1

// Find odd number in array
array.find((element) => element % 2 !== 0); // 1
array.findIndex((element) => element % 2 !== 0); // 0

Find multiple elements in an array

Use the filter array method to find multiple elements in array.

const array = [1, 2, 3, 4, 5, 6, 7, 8];

// find all even elements in array
array.filter((element) => element % 2 === 0);
// [ 2, 4, 6, 8 ]

// find all odd elements in array
array.filter((element) => element % 2 !== 0);
// [ 1, 3, 5, 7 ]

Find element in an array of objects by property value

When you have an array of objects, you can use the function parameter passed to find method to specify the condition to check for finding the element.

const people = [
{ name: "Jack", age: 16 },
{ name: "Jill", age: 19 },
{ name: "Humpty", age: 18 },
];
// Find people older than `18`
people.find((element) => element.age > 18);
// { name: 'Jill', age: 19 }

// Find people younger than `18`
people.find((element) => element.age < 18);
// { name: 'Jack', age: 16 }

// Find people who are `18` years
people.find((element) => element.age === 18);
// { name: 'Humpty', age: 18 }
Last updated on Thu Jan 07 2021
Tags: