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:
trueObjects
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:
trueGetting 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:
OlegCommon 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
trueFunctions used in this recipe
- Array.prototype.includes — Checks whether an array contains a value.
- Array.prototype.some — Checks whether at least one element passes a test.
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.indexOf — Finds a value in an array and returns its index.