JavaScript - Arrays - map
// JavaScript - Array.prototype.map()
The map() method creates a new array with the results of calling a provided
function on every element in this array.
var new_array = arr.map(callback[, thisArg])
callback: Function that produces an element of the new Array, taking three arguments:
1. currentValue: The current element being processed in the array.
2. index: The index of the current element being processed in the array.
3. array: The array map was called upon.
thisArg: Optional. Value to use as this when executing callback.
The map method returns a new array with each element being the result of the
callback function.
The map method calls a provided callback function once for each element in an
array, in order, and constructs a new array from the results. The callback is
invoked only for indexes of the array which have assigned values, including
undefined. It is not called for missing elements of the array (that is, indexes
that have never been set, which have been deleted or which have never been
assigned a value).
The map method does not mutate the array on which it is called (although
callback, if invoked, may do so).
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
// Using map to reformat objects in an array:
var kvArray = [{key:1, value:10},
{key:2, value:20},
{key:3, value: 30}];
var reformattedArray = kvArray.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// Multiply each element of the array by 2:
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// Map the result of querySelectorAll:
var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
return obj.value;
});
// Reverse a string:
var str = '12345';
Array.prototype.map.call(str, function(x) {
return x;
}).reverse().join('');
page revision: 1, last edited: 14 Nov 2016 20:30





