DEV Community

Ali Taha Shakir
Ali Taha Shakir

Posted on

map() Array Method

Lets take a look at JavaScript map() method.

The map() method executes a callback function for each element of array. That callback function accepts between one and three arguments:

  • Current Value (required) - The value of the current array element being processed in loop.
  • Index (optional) - The current element's index number.
  • Array (optional) - The array map() was called upon.

That sounds a lot like forEach() method. But where forEach() method is allowed to mutate the original array and will always return undefined, map() method will always utilize the return values and actually returns a new Array of the same size.

Considering that we have the following array below:

const numbersArray = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Let’s apply foreach() method on above array.

Note: that you would never return from a forEach() method as the return values are simply discarded:

numbersArray.forEach((number, index) => {
    return numbersArray[index] = number * 2;
});
console.log(numbersArray);
Enter fullscreen mode Exit fullscreen mode

result will be:

numbersArray = [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Now here’s an example with map() method:

const numbersTimesTwo = numbersArray.map(number => {
    return number * 2
})
console.log(numbersTimesTwo)
Enter fullscreen mode Exit fullscreen mode

result will be:

numbersTimesTwo = [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Let’s look at another example: say you received an array which contains multiple objects – each one representing a student. The thing you really need in the end, though, is an array containing only the id of each student.

// What you have
let students = [
  { id: 12, name: 'Chadwick Boseman' },
  { id: 18, name: 'Chris Hemsworth' },
  { id: 27, name: 'Chris Evans' },
  { id: 56, name: 'Scarlett Johansson' }
];

// What you need
[12, 18, 27, 56]
Enter fullscreen mode Exit fullscreen mode

There are multiple ways to achieve this. You might want to do it by creating an empty array, then using forEach() method to push the id in an empty array

let studentsIds = [];
students.forEach(function(student) {
  studentsIds.push(student.id);
});
Enter fullscreen mode Exit fullscreen mode

OR we can make this simpler and use map() method

let studentsIds = students.map(function(student) {
  return student.id
});
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the ES6 arrow function representation for simplifying the code:

const studentsIds = students.map(student => student.id);
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this post please share, and follow me on DEV.to or Twitter if you would like to know as soon as I publish a post! 🔥

Top comments (0)