Determine whether an array contains a value [duplicate]
Solution 1:
jQuery has a utility function for this:
$.inArray(value, array)
Returns index of value
in array
. Returns -1
if array
does not contain value
.
See also How do I check if an array includes an object in JavaScript?
Solution 2:
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;
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage