myArray = Array(/*element1, element2, etc...*/);
// If the array 'myArray' contains the element 'valueWeSearch'
if(myArray.includes(valueWeSearch))
{
// Do something
}
How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
// check if an array INCLUDES a certain value
//array for includes()
let numbers = [1, 2, 3, 4, 5]
// either true or false
numbers.includes(2) // returns true, the numbers array contains the number 2
numbers.includes(6) // returns false, the numbers array DOESNT contain the number 6
let isInArray = arr.includes(valueToFind[, fromIndex])
// arr - array we're inspecting
// valueToFind - value we're looking for
// fromIndex - index from which the seach will start (defaults to 0 if left out)
// isInArray - boolean value which tells us if arr contains valueToFind
javascript - Determine whether an array contains a value
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};