Skip to content

Instantly share code, notes, and snippets.

@nekman
Created June 19, 2012 21:11
Show Gist options
  • Save nekman/2956557 to your computer and use it in GitHub Desktop.
Save nekman/2956557 to your computer and use it in GitHub Desktop.
Find items in an array.
/*!
I can have reinvented the wheel...But it is good to do so, just for the education :)
Anyway!
Finds a item in an array, by the given search string and/or matching function.
Usage:
------------------
arrayFind(array, { search : <search string> , matcher : <function> });
arrayFind(array, { matcher : <function> });
Example:
------------------
//Returns an array with one object: {name:'foo'}
var result = { packages : [{name:'foo'}, {name:'bar'}, {name:'baz'}] };
arrayFind(result.packages, {
search : 'foo',
matcher : function(search) {
var name = this.name;
return name && name.match(search,'g');
}
});
//Returns an array of even numbers: [2,4,6]
arrayFind([1,2,3,4,5,6], {
matcher : function() {
return this % 2 === 0;
}
});
//Returns an empty array: []
arrayFind([1,2,3,4,5,6]);
*/
var arrayFind = function(items, options) {
var results = [];
if (!options) {
return results;
}
var predicate = options.matcher,
search = options.search,
len = items.length,
i = 0;
for ( ; i < len; i++) {
var item = items[i];
if (item && predicate.call(item, [search])) {
results.push(item);
}
}
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment