Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a value exists in an array

Short answer

The array's includes() method looks for a value:

console.log(['red', 'green', 'blue'].includes('green'));

Output:

true

Objects

Objects are compared by reference, so describe the condition with a function in some():

const users = [{ id: 1 }, { id: 2 }];
 
console.log(users.some((user) => user.id === 2));

Output:

true

Getting the element itself

If you need the matching object, use find():

const users = [{ id: 1, name: 'Anna' }, { id: 2, name: 'Oleg' }];
 
console.log(users.find((user) => user.id === 2).name);

Output:

Oleg

Common mistake

indexOf() cannot find NaN, while includes() can:

const values = [1, NaN, 3];
 
console.log(values.indexOf(NaN));
console.log(values.includes(NaN));

Output:

-1
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.