The simplest solution for a contains
function, would be a function that looks like this :
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf
, you could use this polyfill, which I got from the MDN :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}