Filter is also going to use each. It's going to run a truth test on each item in the array. If the test on the item equates to true, then it's going to push this item into a new array, and finally the function will return this new array.
A quick example would be to take an array of numbers, and return only the even numbers.
var test = _.filter([1,2,3,4,5,6], function(item){
return item % 2 === 0 ;
});
test will equal = [2,4,6]
The test of % 2 === 0 will return true if the number is even and false if it is odd. How this works inside the function, I'll show below:
var _ = {};
_.each = function(collection, iterator){
if(Array.isArray(collection)){
for(var i = 0; i < collection.length; i ++){
iterator(collection[i], i, collection);
}
}
else{
for(var key in collection){
iterator(collection[key], key, collection);
}
}
}
_.filter = function(collection, test) {
var filterArray = [];
_.each(collection, function(item){
if(test(item)){
filterArray.push(item);
}
});
return filterArray;
}
Once again, I've included the each function above the filter function, because filter will use each to iterate through its array.
Since filter will be returning a new array with all of the items that pass the truth test, we start out be declaring a new local variable, I named mine filterArray and set its value to an empty array.
Next, I called each, which will be fed the same collection fed to filter and then I hard wired in a function for each. In this function I make a conditional statement, which says that if the test (which is the function fed to filter) which is fed the item === true, then push that item to the new array.
Finally, when the entire array has been iterated through the filterArray is returned. This is the new array holding all those items that passed the truth test.
Questions?
#1 - How does the function given as an argument to filter have access to 'item' which is supplied inside of the each function?
Look where the function is run. It is passed all the way down inside the each function, and that is why it has access to 'item'. Each then produces a side effect by pushing to filterArray, which is declared outside of each inside the filter function.
No comments:
Post a Comment