Introduction to the JavaScript Array map() Method

The JavaScript Array map() method creates a new array by populating the results of its parent array elements using a specific function or callback method on each element. As long as an array value is present, it will be included in the resulting array, including values that are undefined.

The JavaScript Array map() Method Laid Out

Here is the syntax for the map() method:

var new_array = parent_array.map(function callback(current_value [, index [, array]]) [, this_value]);

And here are the details regarding each of the map() method's parameters:

  • callback: A function that is called for every element of parent_array. Each time the callback is executed, its returned value gets appended to new_array.
  • current_value: The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array map() was called upon.
  • this_value (optional): Holds the value of this when executing the callback.

The return value, in this case new_array, becomes the new array with each element being the result of the callback function.

A Basic Example

Let's take an array of drink types and output them to the console. Generally, we would do this with a for loop, iterating over the array one at a time:

var drinks = ["Coffee", "Tea", "Soda", "Wine"];

for (var i = 0; i < drinks.length; i++) {
console.log(drinks[i]);
}

// output:
// Coffee
// Tea
// Soda
// Wine

Here, we're looping over the array elements one at a time to access and output their values to the console log.

A similar method, using the map() method, allows you to map directly to the array itself and will automatically iterate through all elements until the end of the array is reached:

var drinks = ["Coffee", "Tea", "Soda", "Wine"];

drinks.map(function(val, i) {
console.log(val);
});

// output:
// Coffee
// Tea
// Soda
// Wine

The examples are very similar. However, in the latter code snippet, the array mapping only occurs once, while easily allowing you access to the array's current index position and its current value.

Performing Calculations on Numeric Array Values

Using a for loop and map() method examples again, we can show off the true power of the map() method.

In the for loop, we can iterate over the following array of numeric values one at a time, perform a calculation by multiplying each of the values by 2, then output the values once all calculations have successfully completed:

var array = [1, 4, 9, 15];

for (var i = 0; i < array.length; i++) {
array[i] *= 2;
}

console.log(array);
// [2, 8, 18, 30];

Or we can use the shorthand option with the map() method by completing all calculations with one line of code versus iterating over each element individually:

var array = [1, 4, 9, 15];
var map = array.map(i => i * 2);

console.log(map);
// [2, 8, 18, 30];

Creating an Array from a Set of HTML Elements

The coolest, and most useful way of using the map() method, in my opinion, is by using the shorthand method for accessing data within HTML elements.

Say, for example, you have a list drinks that you need to convert to a JavaScript array:

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Soda</li>
<li>Wine</li>
</ul>

You can do so in a for loop by iterating over each list item:

var drinks = [];

for (var i = 0; i < $("li").length; i++) {
var drink = $("li").eq(i).text();

drinks.push(drink);
}

console.log(drinks);
// ["Coffee", "Tea", "Soda", "Wine"]

Or you can use the shorthand option using the map() method, which will do the dirty work for you in a single line of code:

var drinks = $("li").map(function() { return $(this).text(); }).get();

console.log(drinks);
// ["Coffee", "Tea", "Soda", "Wine"]

The outputs are identical. It's way cleaner and easier to read and code, and, unlike objects, the shorthand method will retain the sort as displayed in your HTML, whereas objects are known to rearrange and randomize the data at will.

You could also implement a similar example where a list of ID's or even data attribute values are returned from a set of HTML elements.

When it comes to real-world examples, I use the map() method with HTML elements most of the time when I need to access particular bits of data from within the element's attributes.

Accessing Object Data with this

There may be a scenario where you need to access related data within a parent object, or you want to keep all data and functions within the same object like the following object declaration:

var obj = {
text: "Item",
items: [1, 2, 3],
show: function() {
this.items.map(function(item) {
console.log(this.text, item);
}, this);
}
};

Here, you're creating an object containing a string, an array, and a function. And you want all data accessible within the object's function call show() and that function's callback method.

The function call to obj.show() will output the text "Item" along with it's item number in each map() loop iteration:

obj.show();

// output:
// Item 1
// Item 2
// Item 3

Conclusion

That pretty much covers JavaScript's Array map() method. It's a very useful method when you need to gather or manipulate data quickly, and is an easy enough concept to remember for your future projects.