22
map - Higher Order Function in JavaScript - in Depth
In modern JavaScript, we have a very powerful method which is map.
Map method runs/loops on an array (not on object) and runs a function on each element of the array, the returned value of that function becomes the new element of the new array.
Confused? don't worry, I will cover every detail and make you comfortable with map function
let's get started.
const drugs = ["facebook", "whatsapp", "instagram"]
// map
const newDrugs = drugs.map(function(value){
return "the " + value;
})
//console newDrugs
["the facebook", "the whatsapp", "the instagram"]
map has taken every element of the array drugs and ran function on it, returned value of the function (with "the ") has become the new value of the new array
Arrow function makes it a bit more clean
// map
const newDrugs = drugs.map(value => "the ")
It is the each single element of array
const newDrugs = drugs.map(function(element){
return "the " + element;
})
It is the index of each single element of array
const newDrugs = drugs.map(function(element, index){
console.log(index) //console 0, 1, 2
return "the " + element;
})
It is the initial array (drugs) which we are mapping
const newDrugs = drugs.map(function(element, index, array){
console.log(index)
console.log(array) //console every time ["facebook", "whatsapp", "instagram"]
return "the " + element;
})
We can set the value of our own 'this' inside map ;). Let me show you how.
Define the new object as below
const newDrugs = drugs.map(function(element){
return "the " + element + " by " + this.ceo;
}, {
ceo: 'mark zuckerburg',
})
//console
["the facebook by mark zuckerburg", "the whatsapp by mark zuckerburg", "the instagram by mark zuckerburg"]
map() builds the new array and return it, when you don't want returned array, use forEach or for...of
We can reformat the array of objects using map
const ourArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}]
let reformattedArray = ourArray.map(x => {
let newObj = {}
newObj[x.key] = x.value
return newObj
})
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
22