Skip to content

Instantly share code, notes, and snippets.

@toadkicker
Last active December 21, 2015 09:59
Show Gist options
  • Select an option

  • Save toadkicker/6288676 to your computer and use it in GitHub Desktop.

Select an option

Save toadkicker/6288676 to your computer and use it in GitHub Desktop.
Stop writing for loops
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;
}
}
@toadkicker

Copy link
Copy Markdown
Author

//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 });

@toadkicker

Copy link
Copy Markdown
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