Skip to content

Instantly share code, notes, and snippets.

@rouzbeh84
Last active September 3, 2015 06:19
Show Gist options
  • Save rouzbeh84/3a57e0118d2052fab4eb to your computer and use it in GitHub Desktop.
Save rouzbeh84/3a57e0118d2052fab4eb to your computer and use it in GitHub Desktop.
function filter(collection, callback) {
//set empty array as it asks for array of items for output
var output = [];
// check if array and if so loop through collection with for loop
if(Array.isArray(collection)) {
for(var i = 0; i < collection.length; i++) {
//if callback functions returns 'truthy' statement
if(callback(collection[i], i, collection)) {
//push to output array
output.push(collection[i]);
}
}
} else {
// it is an object and use for/in to go through the collection
for(var key in collection) {
//if callback functions returns 'truthy' statement
if(callback(collection[key], key, collection)) {
//push to output array
output.push(collection[key]);
}
}
}
//return final output array when finished looping through collection
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment