Javascript Array map()

Introduction

Javascript array map() method creates a new array by calling mapping function on each element.

let new_array = arr.map(function callback( currentValue[, index[, array]]) {
}[, thisArg])
Parameter
Optional
Meaning
callback




Not




function called for every element.
The callback function takes three arguments:
currentValue - the current element being processed.
index - Optional, the index of the current element.
array - Optional, the array itself.
thisArg
Optional
value to use as this when executing callback.

It is not called for missing elements of the array.

The following code calculates the square roots one each array element.

let numbers = [1, 4, 9]
let roots = numbers.map(function(num) {
    return Math.sqrt(num)
})
console.log(numbers);/*from   w  w  w.  jav  a 2s  .com*/
console.log(roots);

Using map to reformat objects in an array

let kvArray = [{key: 1, value: 10},  
               {key: 2, value: 20},  /*from  ww  w  .  java2 s  . c  om*/
               {key: 3, value: 30}]

let reformattedArray = kvArray.map(obj => {
     let rObj = {};
     rObj[obj.key] = obj.value+1;
     return rObj;
})

Double each element in the array

let numbers = [1, 4, 9]
let doubles = numbers.map(function(num) {
  return num * 2/*w  w w .j av  a  2  s.com*/
})
console.log(numbers);
console.log(doubles);

Get the full name for each person in the array:

var persons = [//from w w w .j a va 2  s. c om
  {firstname : "A", lastname: "X"},
  {firstname : "B", lastname: "Y"},
  {firstname : "C", lastname: "Z"}
];


function getFullName(item) {
  var fullname = [item.firstname,item.lastname].join(" ");
  return fullname;
}

console.log(persons.map(getFullName));



PreviousNext

Related