Array.contains(array, value)

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
}

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s