Map also returns a new array built out of the old array. It simply runs a function on each item, and then returns that result.
Map uses each so I'll past that here too:
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);
}
}
}
_.map = function(collection, iterator) {
var mapArray = [];
_.each(collection, function(item){
mapArray.push(iterator(item));
})
return mapArray;
}
So, let me walk through map. First a local variable is declared, mapArray and is set to an empty array. Then map calls each, feeds it the collection, and hard wires in a function to each. This function will take item(this parameter could have any name, but by having the function take only one parameter I will only be using each item in the array, not the index number, or the collection itself) and then it will push to mapArray the value returned from the function fed item. This function fed item is what is fed to map when it is called. The parameter is named iterator when map is rewritten here, so the word iterator must be used inside each.
Let me give an example of when map might be used.
Take an array of numbers and multiply each by 80.
var numbers = [2,4,7,6,5,6,8,9,1,2];
var example = _.map(numbers, function(num){
return num * 80;
})
console.log(example);
This is what will be printed to the console : [ 160, 320, 560, 480, 400, 480, 640, 720, 80, 160 ]
When I called map I gave it two arguments. The collection, and the I wrote a function. This function is referred to as iterator in the map rewrite. This iterator is passed into each, that is why it has access to item. The function each takes the iterator and feeds it three arguments, the value, the index number, and the collection itself. If the function you write has only one parameter, then that will be fed with the value as an argument. This value I speak of is often referred to as item.
The main advantage to using map over building for loops to do the same thing, is in reducing the size and number of characters involved in the code.
No comments:
Post a Comment