Last active
September 3, 2015 06:19
-
-
Save rouzbeh84/3a57e0118d2052fab4eb to your computer and use it in GitHub Desktop.
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
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