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]
Top comments (0)