
Javascript Array Helper: map
The purpose of the map() array helper is to execute a function for every array element and return a new array. The key to remember with this method is that a new array will be returned (you are not changing the original array).
A Practical Example
Suppose we have an array of items and we want to format them in a new array as HTML list items. Here is how you could do it using map().
First, let’s look at how we would do this in older ES5 javascript.
var items = ["Item 1", "Item 2", "Item 3"]; var listItems = []; for (var i=0; i<items.length; i++) { listItems.push("<li>"+items[i]+"</li>"); } console.log(listItems);
Javascript map Helper
Here is how the example above would be re-written using the map helper.
var items = ["Item 1", "Item 2", "Item 3"]; var listItems = []; listItems = items.map(function(item) { return "<li>"+item+"</li>"; }); console.log(listItems);
The way this works is that for each array element a callback function will get called where you can do some kind of transformation and return the value. The end results is a brand new array with the transformed elements.
With the map function all you have to worry about is the modification you want to do on each element, all the logic of adding it to the end of the new array is handled automatically by the map function.
Hope this helps, in my next post I will discuss if the array .filter function.