Array Map Method in JavaScript

Array Map Method in JavaScript is used to create a new array of required elements from the existing array or array of objects.

The map method calls a function in order for all elements present in the parent array.

The map() method does not make changes in the original array and it is only valid for elements in an array containing values.

The syntax of Array Map Method in JavaScript.

//example


array.map(function(currentValue, index, arr), thisValue)



//

array : The parent array, where to extract new array.

.map() : This is the syntax of map method on parent array.

function() : A function is required to be run for all the elements present in the parent array. for example, consider there are 5 elements in an array. Then the function() will run 5 times.

currentValue : This is current value of element and it is required.

index : It shows the current index against the element of an array. It is optional.

arr : It holds the array object and it is optional parameter.

thisValue : It is an optional parameter. It holds value to be passed to the function called its “this” value. If this is empty, then the ‘undefined‘ will be passed.

Examples of Array Map Method in JavaScript.

Consider the following simple array.

//example
// Array Map Method in JavaScript

var numbers = [10, 20, 30, 40, 50];

//

Then what if we want a new array by adding 5 on each element.

//example


var newArray = numbers.map(addFiveFunction)

function addFiveFunction(number) {
  return number + 5;
}


//

You can write the same example in ES6 as follow.

//example


var newArray = numbers.map( (number) => {
return number + 5;
});



//

Or you can simply write it by removing the ‘return’ (reserved word) and curly brackets.

//example


var newArray = numbers.map( (number) => number + 5);


//
Array Map Method in JavaScript
Array Map Method in JavaScript

Example with array of object

lets consider the following array of objects.

The objects are variables and contain many values. These values are written as name: value pairs. The name and value are separated by a full colon.

//example 


var students = [
  {firstName : "John", lastName: "Doe" , rollNo : 1},
  {firstName : "Emma", lastName: "Watson", rollNo : 2},
  {firstName : "Carrie", lastName: "Holmes", rollNo : 3}
];


//

Now create new array of first name only.

//example


var first = persons.map(function(student){
return student.firstName;
});

// ["Malcom","Kaylee","Jayne"]


//

Using the arrow function with map method in JavaScript it can be simplified as,

//example


var first = persons.map( (student) => student.firstName );

// output will be same as mentioned above


//

Learn Array Map Method in JavaScript in detail with a YouTube video

Learn about JavaScript date and time formats in details

Similar Posts