25 March 2024

array-method-map image

JavaScript Array Methods: Understanding `map`

JavaScript's array methods are powerful tools for handling data. After forEach, let's delve into the map method. Unlike forEach, which only iterates over array items, map goes a step further. It iterates over each item, allowing us to modify each one and then returns a new array reflecting those changes. This is particularly useful for transforming data.

Basic Example

Consider we have an array of fruits:

const fruits = ['apple', 'mango', 'avocado']
const fruitsUpperCase = fruits.map((fruit, index) => {
  return fruit.toUpperCase()
})
console.log(fruitsUpperCase) // ['APPLE', 'MANGO', 'AVOCADO']

Here, map is used to transform each fruit name into uppercase letters, demonstrating how we can modify array data and capture the results in a new array.

Real-Life Example

Imagine we're managing a list of products currently out of stock, outOfProducts, and we need to transform this list. Specifically, we want to convert each product name into an object that includes both the name of the product and its nextDeliveryTime. This transformation allows us to inform users when out-of-stock items will be available again.

const NEXT_DELIVERY_TIME = '05.05.24'

const outOfProducts = ['apple', 'mango', 'avocado']

const outOfProductsFullData = outOfProducts.map((fruit) => {
  return {
    name: fruit,
    nextDeliveryTime: NEXT_DELIVERY_TIME,
  }
})
console.log(outOfProductsFullData)
/*
[
    {
        "name": "apple",
        "nextDeliveryTime": "05.05.24"
    },
    {
        "name": "mango",
        "nextDeliveryTime": "05.05.24"
    },
    {
        "name": "avocado",
        "nextDeliveryTime": "05.05.24"
    }
]
*/

Through this example, we see how map can be a powerful tool for data transformation, enabling us to prepare and present data in a format that's more useful for our application's needs.

Thanks for hanging out! 👋