Created
May 2, 2014 15:12
-
-
Save navarroaxel/e809723100d30af7c60a to your computer and use it in GitHub Desktop.
Array extensions in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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