The .map
function accepts an array and an iteratee function, the iteratee produces a transformed copy of each array object.
The iteratee function provides 3 arguments
item
- The current iterated objecti
- The index of the iterated objectlist
- A reference to the original array/listThe new Array will be of the same length as the old array but will hold the trasformed objects
Example:
_.map([1, 2, 3, 4], function(item, i, list) {
return (item*item);
});
// [1, 4, 9, 16]
A more concise way to write the above example using ES6 would be
_.map([1, 2, 3, 4], (item, i, list) => {
return (item*item);
});
or using an inline lambda expression
_.map([1, 2, 3, 4], (item, i, list) => (item*item));
Map is also useful when you want to pluck properties from objects and make an array of them
Example:
let people = [{name: 'he-man', age: 22}, {name: 'man-at-arms', age: 44}];
_.map(people, function(item) {
return item.name;
});
// ['he-man', 'man-at-arms']