Check if Value is in Array JavaScript

March 3rd, 2023

There are multiple ways to check if array contains a value:

  • includes, find, filter, indexOf, some, for loop (basic javascript)

  • _includes, _contains (lodash, underscore)

includes

doesn't skip missing values

1arr.includes(value)
2arr.includes(value, fromIndex)
3 
4 
5[1, 2, 3].includes(3, 3); // false
6[1, 2, 3].includes(3, -1); // true
7 
8[1, 2, NaN].includes(NaN); // true

indexOf

skips missing values

1// if indexOf(value) is >= 0, then arr includes value (value is in array)
2arr.indexOf(value) >= 0
3arr.indexOf(value) != -1

for loop

1function contains(arr, value) {
2 for (let i = 0; i < arr.length; i++) {
3 if (arr[i] === value) {
4 return true;
5 }
6 }
7 return false;
8}

underscore: _contains / _includes

1_.contains(arr, value)
2// or the same
3_.includes(arr, value)

lodash: _includes

1_.includes(arr, value, [from])

filter

1function contains(arr, x) {
2 return arr.filter(function(elem) { return elem == x }).length > 0;
3}

find

returns the value of the first element in the provided array that satisfies the provided testing function

1const value = 3
2 
3array.find(x => x === value)

some

tests if at least one element in the array passes the test implemented by the provided function

1array.some(x => x === 3)