Last active
December 21, 2015 09:59
-
-
Save toadkicker/6288676 to your computer and use it in GitHub Desktop.
Stop writing for loops
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
| if (!Array.prototype.first) | |
| { | |
| Array.prototype.first = function(predicate) | |
| { | |
| "use strict"; | |
| if (this == null) | |
| throw new TypeError(); | |
| if (typeof predicate != "function") | |
| throw new TypeError(); | |
| for (var i = 0; i < this.length; i++) { | |
| if (predicate(this[i])) { | |
| return this[i]; | |
| } | |
| } | |
| return null; | |
| } | |
| } |
Author
Author
I got tired of writing for loops to iterate through json
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//usage
var items = [
{ Name : "Matthew", Id : 1 },
{ Name : "Mark", Id : 2 },
{ Name : "Luke", Id : 3 },
{ Name : "John", Id : 4 }
];
// Find the item with Id === 3
var matching = items.first(function(i) { return i.Id === 3 });