ES6 - Array map method

ES6 JavaScript

In this ES6 tutorial we are going to learn about the array map method. So, let's get started.

We use the map method to iterate over the elements of an array and perform some operation on each of the elements. The Map method returns a new array that has same number of elements as the original array.

Map and array

Let's say we have an array of integer values and we want to double each values and return a new element. So, for this we can use the map method.

Here is a code that uses the map method on the array of integers and returns a new array containing doubled values.

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});

So, in the above code we are passing an anonymous function to the map method. This function is called for every element of the array.

We can modify the above code using arrow function like the following.

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => {
  return number * 2;
});

And since there is only one statement inside the arrow function and it is a return statement so we can further simplify it like the following.

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => number * 2);

Map and array of objects

Let's say we have an array of objects and each object consists of player detail and score. Let's say we want to create an array of objects consisting of username and score. For this we can use the map method.

const scoreboard = [
  {
    firstName: 'Jane',
    lastName: 'Doe',
    score: 210,
    username: 'janedoe',
  },
  {
    firstName: 'John',
    lastName: 'Doe',
    score: 100,
    username: 'johndoe',
  }
];

const userScore = scoreboard.map(userscore => {
  const { username, score } = userscore;
  return { username, score };
});

console.log(userScore);

In the above code we have the scoreboard variable that holds the score of each player. Next, we create a new variable userScore to save the array that will be returned when we use map on the scoreboard variable. The above code will return the following output.

[
  { username: 'janedoe', score: 210 },
  { username: 'johndoe', score: 100 }
]

To learn more about destructuring check ES6 - Destructure Array and ES6 - Destructure Object tutorials.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT