HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I check if a JavaScript array includes a specific value?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptcheckhowvaluecanincludesspecificarray

Problem

You can use Array.prototype.includes() to check if an array contains a primitive value. This is the most convenient option when working with strings, numbers, booleans, symbols, null or undefined. You can even specify an index as a secondary parameter to start searching from.
> [!NOTE]
>
> This code snippet can be easily extended to check if an array includes any or all values in another array.
Unlike primitive values, you can't use Array.prototype.includes() to check if an array includes an object. This comes down to how JavaScript compares values and the fact that objects are reference types. I highly recommend reading the previous article about object comparison, as I won't be going into detail on how to compare objects here.

Solution

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

array.includes(3); // true
array.includes(6); // false
array.includes(3, 3); // false


>
> This code snippet can be easily extended to check if an array includes any or all values in another array.
Unlike primitive values, you can't use Array.prototype.includes() to check if an array includes an object. This comes down to how JavaScript compares values and the fact that objects are reference types. I highly recommend reading the previous article about object comparison, as I won't be going into detail on how to compare objects here.
Due to this difference between primitive values and objects, you can't use Array.prototype.includes() to check if an array includes an object. However, provided you implement a deep equality function, you can use Array.prototype.some() to check if any object matches the shape of another object.

Code Snippets

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

array.includes(3); // true
array.includes(6); // false
array.includes(3, 3); // false
const array = [{ a: 1 }, { a: 2 }, { a: 3 }];

const equals = (a, b) => Object.keys(a).every(key => a[key] === b[key]);

array.some(item => equals(item, { a: 2 })); // true
array.some(item => equals(item, { a: 4 })); // false

Context

From 30-seconds-of-code: array-includes-value

Revisions (0)

No revisions yet.