why to use JavaScript map() ?

why to use JavaScript map() ?

·

3 min read

Map function is used to applying the some operation on each element in the array and return the new array .

Original array is not modified instead a new array is returned .

Simple map()

Ok here is a simple example to apply a discount on all the items price.

const prices=[100,500,120,250,450]
const newPrices = prices.map(discount) 
// appy 10 discount on prices 
function discount(price){ // (price,indexofprices,prices)
return price-10;
}
console.log(newPrices); //[90, 490, 110, 240, 440]

We can simplify further using arrow and anonymous functions .

const prices=[100,500,120,250,450]
const newPrices = prices.map(price=>price-10)
console.log(newPrices); //90, 490, 110, 240, 440]

Looks pretty isin't it . Here the prices array still has the same values .

For Array reformatting

Let's say we have an array of product details as below .

const products = [{
    name: 'iphone',
    price: 1000
  },
  {
    name: 'ipad',
    price: 1200
  }, {
    name: 'imac',
    price: 5000
  }, {
    name: 'iwatch',
    price: 500
  }, {
    name: 'ipod',
    price: 200
  }
]
// make an array with only the prices of the products .
const prices = products.map(product =>product.price)
console.log(prices);
//[1000, 1200, 5000, 500, 200]

We can get an array with only the prices from the object array .

Also if you want to apply some discount and return the array of the products as below .

const products = [{
    name: 'iphone',
    price: 1000
  },
  {
    name: 'ipad',
    price: 1200
  }, {
    name: 'imac',
    price: 5000
  }, {
    name: 'iwatch',
    price: 500
  }, {
    name: 'ipod',
    price: 200
  }
]
const discountedProducts = products.map(product => {
  var temp = {}
  temp['name'] = product.name;
  temp['price'] = product.price - 10;
  return temp;
})
console.log(discountedProducts);
/* [{
  name: "iphone",
  price: 990
}, {
  name: "ipad",
  price: 1190
}, {
  name: "imac",
  price: 4990
}, {
  name: "iwatch",
  price: 490
}, {
  name: "ipod",
  price: 190
}] */

If there are no values in the array , map operation is not applied . i.e. the function is not called.

const temp=[ ]
console.log(temp.map(i=>i+1)) // [ ]

To simplify further you may think of map can be used to apply some operation on every element of an array .

Let me know more scenarios you have used a map() in the comments .