JS map()

map() is an array utility function that you’re probably either intimately familiar with or, like me, need to learn.

In a nutshell, map() creates a new array out of the results of calling a given function on every element on the array on which it’s called.

There are implementations of map() in native JS, jQuery and UnderscoreJS. All other things being equal, Underscore’s version is the most performant.

map() is a ‘collection function’, meaning it works on either Arrays or Objects

If our collection is an Array, map() will put each value through a transformational function, passing the value at each index to the array to the callback function as the first parameter, the index as the second and the whole array as the third.

var collection = [1, 2, 3];

_.map(collection, function(val, index, array){ return num * 3; });

// returns array -> [3, 6, 9]

Similarly, if our collection is an Object, map() will pass the the value and key if each attribute, as well as the whole object.

var collection = {one: 1, two: 2, three: 3};

_.map(collection, function(val, key, object){ return num * 3; });

// returns array -> [3, 6, 9]