DEV Community

Ashutosh
Ashutosh

Posted on

1 4

map - Array Function

The map function creates a new array populated with the results of the calling function.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Syntax :

let new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])

callback  - a required function which takes in currentValue, index, the array as parameters
currentValue  -  required parameter. This is the current value of the item in the array
index  -  optional parameter. This is the index of the item that is selected
array  -  optional parameter. This is the array on which map function gets executed.

the map function is called for each item in the array, such that the result is returned as a new processed item as per requirement.

Mapping an array of numbers to an array of square roots

let numbers = [1, 4, 9]
let sum = numbers.map(function(num) {
    let add = 5;
    add += num
    return add;
})
// sum is now     [6, 9, 14]
// numbers is still [1, 4, 9]

Using map function to reformat objects in an array

let kvArray = [{key: 1, value: 10}, 
               {key: 2, value: 20}, 
               {key: 3, value: 30}]

let reformattedArray = kvArray.map(obj => {
   let rObj = {}
   rObj[obj.key] = obj.value
   return rObj
})
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}], 

// kvArray is still: 
// [{key: 1, value: 10}, 
//  {key: 2, value: 20}, 
//  {key: 3, value: 30}]

Mapped array contains undefined

let arr = ["We", "Are", "Bros", 4]
let filteredArr = numbers.map(function(item, index) {
  if (index < 3) {
     return item
  }
})
// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredArr is ["We", "Are", "Bros", undefined]
// numbers is still ["We", "Are", "Bros", 4]

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay