Skip to content

Instantly share code, notes, and snippets.

@juliovedovatto
Created November 25, 2016 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliovedovatto/dc2acf0112247e36b6e37abb684a2fbb to your computer and use it in GitHub Desktop.
Save juliovedovatto/dc2acf0112247e36b6e37abb684a2fbb to your computer and use it in GitHub Desktop.
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