The JavaScript map()
method creates a new array with the results of calling a provided function on every element in this array. For example, lets say you have a small array of numbers called “numbers”:
var numbers = [1, 4, 9];
We can use .map on this array to find the square root of each of the elements in numbers AND assign those results to a new array called ‘roots’:
var roots = numbers.map(Math.sqrt);
// roots now contains [1, 2, 3], numbers still contains [1, 4, 9]
Here is another example of using map()
from the mozilla JavaScript reference site. This example shows how to use map on a String to get an array of bytes in the ASCII encoding representing the character values:
var map = Array.prototype.map; var a = map.call('Hello World', function(x) { return x.charCodeAt(0); }); console.log(a);
which yields:
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
These values can be independently verified with my JavaScript Ascii Engine!
For more information about the .map() function see:
https://www.w3schools.com/jsref/jsref_map.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map