Check if an array contains an element in JavaScript
In JavaScript, there are a few ways to check if an array contains an element. Depending on if you need to know if it contains an exact value, or match a criteria, you have different options.
Using Array.includes to check for an exact value
With Array.includes()
you can check that your array contains an exact value you are looking for. For example:
const trees = ['oak', 'willow', 'maple', 'yew', 'magic'];
console.log(trees.includes('oak')); // true
console.log(trees.includes('normal')); // false
However, if your array contains objects, Array.includes() may not work as expected because it checks for the same object reference, not just the content. Also, it won’t be sufficient if you need to perform more specific checks.
const trees = [
{name: 'oak'},
{name: 'willow'},
{name: 'maple'},
{name: 'yew'},
{name: 'magic'},
];
console.log(trees.includes({name: 'oak'})); // false
Using Array.find() and Array.some()
In the case of objects, or having to do specific checks, you can use the find
and some
functions.
They both work the same, except that find
will return the value it found or undefined
if nothing was found, while some
will return true
if any values match, and false
if they don’t. Both functions will stop the moment they find any value that matches. So if you have multiple values that match your check, the first one will be returned.
To give some examples:
const trees = [
{name: 'oak'},
{name: 'willow'},
{name: 'maple'},
{name: 'yew'},
{name: 'magic'},
];
console.log(trees.find((tree) => tree.name === 'oak')); // {name: 'oak'}
console.log(trees.some((tree) => tree.name === 'oak')); // true
console.log(trees.find((tree) => tree.name === 'normal')); // undefined
console.log(trees.some((tree) => tree.name === 'normal')); // false
console.log(trees.find((tree) => tree.name.length > 3)); // {name: 'willow'}
With these array method you can easily check if your javascript array contains a specific item, wheter you are dealing with simple values or complex objects.
If you want to get notified of the next blog post, join the newsletter.