Skip to content

Instantly share code, notes, and snippets.

@navarroaxel
Created May 2, 2014 15:12
Show Gist options
  • Save navarroaxel/e809723100d30af7c60a to your computer and use it in GitHub Desktop.
Save navarroaxel/e809723100d30af7c60a to your computer and use it in GitHub Desktop.
Array extensions in JavaScript
Array.prototype.where = function (query) {
if (!query) {
return this;
}
if (typeof(query) == 'function') {
return this.filter(query);
};
return this.filter(function (e) {
var result = true;
for (var key in query) {
var value = query[key];
var elementValue = e[key];
result = result && elementValue == value;
}
return result;
});
}
Array.prototype.any = function (query) {
var result = this.where(query);
return result && result.length > 0;
}
Array.prototype.first = function (query) {
var result = this.where(query);
if (result && result.length > 0) {
return result[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment