Array Map Method in JavaScript

Array Map Method in JavaScript, easy ES6 examples

The array Map Method in JavaScript is useful 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.

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

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

.map(): This is the syntax of the map method on the 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 the current value of the element and it is necessary.

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

arr: It holds the array object and it is an 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 to 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.

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

Array Map Method example with an array of objects

let’s consider the following array of objects.

The objects are variables and contain many values. These values are in name: value pairs. A full colon separates the name and value.

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

Now create a new array of the first name only.

//example
var first = persons.map(function(student){
return student.firstName;
});
// ["Malcom","Kaylee","Jayne"]

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

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 detail

Add comment