Working with JavaScript Arrays, Part 2: Array.prototype.map()

2015-11-27 00:00:00 by Mike

Previously we saw how the filter function can remove duplicate array elements.

Another quite useful JavaScript array function, also introduced in ECMAScript 5.1, is the map function.
Array.prototype.map() provides an elegant way to make a new array whose elements are transformed versions of elements in an original array.
You will commonly see the map function offered as an improved alternative to the traditional JavaScript for loop.

Array.prototype.map()

Purpose: Returns an array of transformed elements corresponding to elements in the input array.

Input:

var kilometers = [10, 30, 92, 53, 31, 79, 41, 49, 51, 91];

Example Usage:

var miles = kilometers.map(function(elem, i) {
return elem * 0.621371;
});

Results:

6.21371, 18.64113, 57.166132, 32.932663, 19.262501, 49.088309, 25.476211, 30.447179000000002, 31.689921000000002, 56.544761