Array.prototype.map()

xiao0042

Alice Xiao

Posted on October 20, 2021

Array.prototype.map()

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:

  1. iterate through every element in the array
  2. apply call back function to each element
  3. 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'];
Enter fullscreen mode Exit fullscreen mode

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;
 });
Enter fullscreen mode Exit fullscreen mode

When you print these array

console.log(solarSystem);
console.log(solarSystem2);
Enter fullscreen mode Exit fullscreen mode

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'
]
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

parameter "array":

const solarSystem4 = solarSystem.map(function(planet, index, originalArray){
    return "This is " + planet + " and the next planet is " + originalArray[index + 1];
});
Enter fullscreen mode Exit fullscreen mode
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
xiao0042
Alice Xiao

Posted on October 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About