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)
doesn't skip missing values
1arr.includes(value)2arr.includes(value, fromIndex)3 4 5[1, 2, 3].includes(3, 3); // false6[1, 2, 3].includes(3, -1); // true7 8[1, 2, NaN].includes(NaN); // true
skips missing values
1// if indexOf(value) is >= 0, then arr includes value (value is in array)2arr.indexOf(value) >= 03arr.indexOf(value) != -1
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}
1_.contains(arr, value)2// or the same3_.includes(arr, value)
1_.includes(arr, value, [from])
1function contains(arr, x) {2 return arr.filter(function(elem) { return elem == x }).length > 0;3}
returns the value of the first element in the provided array that satisfies the provided testing function
1const value = 32 3array.find(x => x === value)
tests if at least one element in the array passes the test implemented by the provided function
1array.some(x => x === 3)