Array.contains(array, value)
Posted: January 10, 2012 Filed under: Javascript | Tags: array, snippets Leave a comment »There are cases where one might want to know whether or not an array contains a certain value. There is no default function for doing this by default, and the other alternative to having a new function is to write out an anonymous function in the callback position of the some method.
var a = ["green", "blue", "black"];
if (a.some(function (el) { return (el === "black"); })) {
// do something;
}
That is extremely tedious, and worse, it makes code harder to read. As such, I sometimes use Array.contains, as defined here:
Array.contains = function (array, value) {
return a.some(function (el) { return (el === value); });
}
After that function is included the example can be modified to the cleaner
if (Array.contains(a, "black")) {
// do something
}