Explain the Master javascript Map Method

Understanding What It Does

The map() method simply mutates (changes) the array it’s being called upon and creates a new array after executing a provided function and applying some effects on each element.

Let’s take a look at a simple example:

 const numbers = [4, 8, 15, 16, 23, 42];   
   const numbersTimesTen = numbers.map(
(number) => number * 10 
 console.log (numbersTimesTen)
/ / 40, 80, 150, 160, 230, 420

Here, we have an array of numbers. The goal is to multiply each number by 10, so we use map() to select each number one by one and complete the operation, the result is stored in a new variable.

Using The Index Parameter

Besides the function that handles what happens to each array element, we can also pass in a second index parameter to our map() call

 const cities = ['London', 'Berlin', ' Paris', 'Rome '];
const cityCodes Lowercase = cities.map(
(city, index) => ' ${index}_${city. toLowe r Case () }'
console. log (cityCodes Lowercase) ;

/ / [0_ london, 1_berlin, 2_paris, 3 rome]

In this case, the goal was to build a numbered code for each city in the array. We can do this by calling .map) and using the index parameter to be able to assign it to each new value inserted in the new array.

The second parameter, just like the first, can be given any name. (id, i, index, etc.)

Mapping Over Objects

The map() method is a great way for you to modify objects in an array, let’s take a look:

 const people = [
{ first: 'Mary', last: 'Watson'},
{ first: 'Peter ', last: 'Parker '},
 const people with Full Names = people. map ((person)=> ({...person, 

full Name : '${person. first} ${person. last}' 
} )
console.log (people With Full Names) ;
/  /{ first: 'Mary', last: 'Jane', full Name: 'Mary Jane'},
/ /{ first: 'Peter', last: 'Parker ', full Name: 'Peter Parker '}

Let’s say we need to add a new full Name property to each object in our array of people. We can do so by calling map() to loop over the array and get access to each person, then use the spread operator to destructive that person into a new object. We then add our full Name property for each person at the end of the destructed object.

Map’s Lost Brother: flatMap()

A similar, not often used method worth taking a look at is the .flatMap( ) method, here’s what it does:

 const values = [10, 20, 30, 40];

const valueswithIndex = values . map (
(value, index) => [value , index]
 console.log(valuesWithIndex) ;
/ / [ [10, 0], [20, 1], [30, 2], [40, 3] ]

 const flatValuesWithIndex = values. flatMap (
(value, index) => [value, index]
 console.log (flatValuesWithIndex);
/ / [10, 0, 20, 1, 30, 2, 40, 3];

As you can see, using the same function, flat Map() returns a flattened version of the values inserted into the initial array while.map() keeps every pair in its own array.

Leave a Reply

Your email address will not be published.