map() method creates a new array with the results of calling a provided function on every element in this array.

Syntax

array.map(callback[, thisObject]);

Parameter Details

  • callback − Function that produces an element of the new Array from an element of the current one.
  • thisObject − Object to use as this when executing callback.

Return Value

Returns the created array.E

Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.

// What you have
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
];
// What you need
[20, 24, 56, 88]

There are multiple ways to achieve this. You might want to do it by creating an empty array, then using .forEach().for(...of), or a simple .for() to meet your goal.

Let’s compare!

Using .forEach():

var officersIds = [];
officers.forEach(function (officer) {
officersIds.push(officer.id);
});

Notice how you have to create an empty array beforehand? Let’s see what it looks like when using .map():

var officersIds = officers.map(function (officer) {
return officer.id
});

We can even be more concise with arrow functions (requires ES6 support, Babel or TypeScript)

const officersIds = officers.map(officer => officer.id);

So how does .map() work? Basically is takes 2 arguments, a callback and an optional context (will be considered as this in the callback) which I did not use in the previous example. The callback runs for each value in the arrayand returns each new value in the resulting array.

Keep in mind that the resulting array will always be the same length as the original array.

Example

Let me explain with the following array

let students = [
{
name: 'Sathish',
tamil: 99,
english: 89,
maths: 97,
science: 96,
social: 96
},
{
name: 'Roja',
tamil: 89,
english: 79,
maths: 87,
science: 96,
social: 90
},
{
name: 'Vimal',
tamil: 77,
english: 89,
maths: 89,
science: 96,
social: 96
}
,{
name: 'Raja',
tamil: 91,
english: 69,
maths: 87,
science: 92,
social: 86
}
];

here i have a array with some students list. Each student have name and some mark details. I want a new array only with student name and total marks. Like the following

[
{"name":"Sathish","total":477},
{"name":"Roja","total":441},
{"name":"Vimal","total":447},
{"name":"Raja","total":425}
]

i am going to use the .map() function to get this one

let totalOnly = students.map(student => {
return {
name: student.name,
total: student .tamil + student .english + student .maths + student .science + student .social }
});