Pages

Tuesday, June 7, 2016

Rewriting Underscore's pluck function

Pluck is very useful working with something that can be quite tricky, an array of objects like this one:

var info = [{name:"Sam", age: 40}, {name: "John", age: 60}, {name: "Bill", age: 70}];

With pluck, one can simply pull out a specific value from each object in the array.  For example, say you wanted all the names, or all the ages.  Pluck can do this for you like so:


var example = _.pluck(info, "name");

console.log(example);

['Sam',  'John', 'Bill' ]  will be printed to the console.



Pluck will use map, and map will use each, so I'll paste all those 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);
    }
  }
}


_.map = function(collection, iterator) {
var mapArray = [];
_.each(collection, function(item){
mapArray.push(iterator(item));
})
    return mapArray;
}



_.pluck = function(collection, key) {
      return _.map(collection, function(item) {
        return item[key]
    })
}

Let's walk through pluck.  Pluck takes two arguments, the collection being dealt with, and the property or key from which the value should be extracted.  In the example above where we called pluck, "name" was the key given and the values were extracted from the key "name".

Pluck calls map, feeds it the same collection, and hard wires in a function that takes item.  Remember, this function is going to be fed to each, this is why it has access to item.  However, because we are dealing with an array of objects the array named info will return the first object if we try this:  console.log(info[0]);

So the item fed to the function in this case is actually the first object in the array.  If you were to type this : console.log(info[0]["name"])  or an alternative way of doing roughly the same thing :
console.log(info[0].name) then 'Sam' would be printed to the console.

So, after the function hard wired to map takes the item as an argument, it then returns the value of item[key], the variable key here is supplied when pluck is called and could be for example, "name".

Values are returned to the functions that called them, so this value is returned to the function hard wired in map, we know map returns a new array and then is returned to pluck via the key word return in front of map.









No comments:

Post a Comment