Array.prototype.map()
Alice Xiao
Posted on October 20, 2021
This is a tutorial on map() methods with explanation and examples.
On MDN, the map() method is described as:
"to create a new array populated with the results of calling a >provided function on every element in the calling array."
Basically, it applies the following steps to the original array:
- iterate through every element in the array
- apply call back function to each element
- return the result to a new array without changing the original array.
Let's look at an example:
First let's create a new array with planet name strings:
const solarSystem = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto'];
And then, we apply .map() method to our solarSystem array to add the string "This is " in front of every element in the array, and save the new array as solarSystem2. This function could be shortened into arrow array.
const solarSystem2 = solarSystem.map(function(planet){
return "This is " + planet;
});
When you print these array
console.log(solarSystem);
console.log(solarSystem2);
You will get:
[
'Mercury', 'Venus',
'Earth', 'Mars',
'Jupiter', 'Saturn',
'Uranus', 'Neptune',
'Pluto'
]
[
'This is Mercury',
'This is Venus',
'This is Earth',
'This is Mars',
'This is Jupiter',
'This is Saturn',
'This is Uranus',
'This is Pluto'
]
The call back function and the element input to the call back function are compulsory parameters, let's now look at other parameters that you could use in this method:
parameter "index":
const solarSystem3 = solarSystem.map(function(planet, index){
return "This is " + planet + " number " + (index+1);
});
parameter "array":
const solarSystem4 = solarSystem.map(function(planet, index, originalArray){
return "This is " + planet + " and the next planet is " + originalArray[index + 1];
});
Posted on October 20, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.