DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on

1

JavaScript Array Methods: Understanding `map`

Image description

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']
Enter fullscreen mode Exit fullscreen mode

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"
    }
]
*/
Enter fullscreen mode Exit fullscreen mode

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! Hit subscribe for more! 👋

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay