Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript: check if the given element is in array
function in_array(value, array) {
if (array.constructor !== Array)
return false;
return array.filter(function(item) { return item == value; }).length > 0;
}
// example
in_array(2, [1,2,3, "foo", "bar"]); // true
// ----------------------------------------------------------------------------------------------------------------------
// extending Array prototype
Object.defineProperty(Array.prototype, 'in_array', {
value: function(value) {
return this.filter(function(item) { return item == value; }).length > 0
},
writable: false,
configurable: false,
enumerable: true
});
// Exemple
[1,2,3, "foo", "bar"].in_array(2); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.