map()
The map()
method calls a function for each item in an array, and creates a new array with the results. Unlike forEach()
, map()
returns a new array and doesn't modify the original one, making it perfect for transforming data.
Syntax
const newArray = array.map(function(currentValue, index, array) {
// return element for newArray
});
Parameters:
- function: Function that produces an element of the new array, taking three possible arguments:
- currentValue: The current element being processed.
- index (optional): The index of the current element.
- array (optional): The original array
map()
was called upon.
Basic usage
Let's look at a simple transformation example using a pizza toppings array. This example is used to order double toppings:
const pizzaToppings = ['cheese', 'pepperoni', 'mushrooms', 'olives'];
const formattedToppings = pizzaToppings.map(topping => {
return "double " + topping;
});
console.log(formattedToppings);
// Output: ["double cheese","double pepperoni","double mushrooms","double olives"]
This will transform the original array value to begin with an uppercase letter:
const pizzaToppings = ['cheese', 'pepperoni', 'mushrooms', 'olives'];
const formattedToppings = pizzaToppings.map(topping => {
return topping.charAt(0).toUpperCase() + topping.slice(1);
});
console.log(formattedToppings);
// Output: ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives']
Using the index parameter
The second parameter gives you access to the current index, which can be useful for various transformations:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
const numberedToppings = pizzaToppings.map((topping, index) => {
return `${index + 1}. ${topping}`;
});
console.log(numberedToppings);
// Output:
// ['1. Cheese', '2. Pepperoni', '3. Mushrooms', '4. Olives']
The function can also be extracted from the map
method, making it more readable and re-usable:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
const listToppings = (topping, index) => {
return `${index + 1}. ${topping}`;
}
const numberedToppings = pizzaToppings.map(listToppings);
console.log(numberedToppings);
// Output:
// ['1. Cheese', '2. Pepperoni', '3. Mushrooms', '4. Olives']
Using the array parameter
The third parameter provides reference to the original array, as used in the following two examples:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
pizzaToppings.map((topping, index, array) => {
const newName = "Double " + topping
console.log("new name: " + newName + " | old name: " + array[index])
});
// Output:
// "new name: Double Cheese | old name: Cheese"
// "new name: Double Pepperoni | old name: Pepperoni"
// "new name: Double Mushrooms | old name: Mushrooms"
// "new name: Double Olives | old name: Olives"
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
const toppingsWithTotal = pizzaToppings.map((topping, index, array) => {
return `${topping} (${index + 1} of ${array.length})`;
});
console.log(toppingsWithTotal);
// Output:
// ['Cheese (1 of 4)', 'Pepperoni (2 of 4)', 'Mushrooms (3 of 4)', 'Olives (4 of 4)']
Working with objects in arrays
The map()
method is useful when working with arrays of objects:
const pizzaMenu = [
{ name: 'Margherita', price: 10, ingredients: ['Tomato Sauce', 'Mozzarella', 'Basil'] },
{ name: 'Pepperoni', price: 12, ingredients: ['Tomato Sauce', 'Mozzarella', 'Pepperoni'] },
{ name: 'Vegetarian', price: 13, ingredients: ['Tomato Sauce', 'Mozzarella', 'Mushrooms', 'Bell Peppers', 'Olives'] }
];
// Create a simplified menu with just names and prices
const simplifiedMenu = pizzaMenu.map(pizza => {
return {
name: pizza.name,
price: pizza.price,
ingredientCount: pizza.ingredients.length
};
});
console.log(simplifiedMenu);
/* Output:
[
{ name: 'Margherita', price: 10, ingredientCount: 3 },
{ name: 'Pepperoni', price: 12, ingredientCount: 3 },
{ name: 'Vegetarian', price: 13, ingredientCount: 5 }
]
*/
Chaining map() with other array methods
One of the most powerful features of map()
is the ability to chain it with other array methods:
const pizzaMenu = [
{ name: 'Margherita', price: 10, spicy: false },
{ name: 'Pepperoni', price: 12, spicy: true },
{ name: 'Vegetarian', price: 13, spicy: false },
{ name: 'Diavola', price: 14, spicy: true },
{ name: 'Hawaiian', price: 12, spicy: false }
];
// Find names of spicy pizzas that cost less than $14
const affordableSpicyPizzas = pizzaMenu
.filter(pizza => pizza.spicy && pizza.price < 14)
.map(pizza => pizza.name);
console.log(affordableSpicyPizzas);
// Output: ['Pepperoni']
Nested map() calls
When working with nested arrays, you can use nested map()
calls. The example uses an array for the stores, and a nested array for the pizzas
:
const pizzaStores = [
{
name: "Store 1",
pizzas: [
{ name: "Margherita", price: 10 },
{ name: "Pepperoni", price: 12 }
]
},
{
name: "Store 2",
pizzas: [
{ name: "Margherita", price: 11 },
{ name: "Vegetarian", price: 13 }
]
}
];
// Get an array of pizza availability across stores
const pizzaAvailability = pizzaStores.map(store => {
return {
store: store.name,
pizzaOptions: store.pizzas.map(pizza => `${pizza.name}: $${pizza.price}`)
};
});
console.log(pizzaAvailability);
/* Output:
[
{
store: "Store 1",
pizzaOptions: ["Margherita: $10", "Pepperoni: $12"]
},
{
store: "Store 2",
pizzaOptions: ["Margherita: $11", "Vegetarian: $13"]
}
]
*/
Practical example: applying discounts
const pizzaOrder = [
{ name: 'Margherita', price: 10, quantity: 2 },
{ name: 'Pepperoni', price: 12, quantity: 1 },
{ name: 'Supreme', price: 15, quantity: 1 }
];
// Apply a 10% discount to all pizzas
const discountedOrder = pizzaOrder.map(item => {
const discountedPrice = item.price * 0.9;
return {
name: item.name,
originalPrice: item.price,
discountedPrice: Math.round(discountedPrice * 100) / 100,
quantity: item.quantity,
totalSaving: Math.round((item.price - discountedPrice) * item.quantity * 100) / 100
};
});
console.log(discountedOrder);
/* Output:
[
{
"name": "Margherita",
"originalPrice": 10,
"discountedPrice": 9,
"quantity": 2,
"totalSaving": 2
},
{
"name": "Pepperoni",
"originalPrice": 12,
"discountedPrice": 10.8,
"quantity": 1,
"totalSaving": 1.2
},
{
"name": "Supreme",
"originalPrice": 15,
"discountedPrice": 13.5,
"quantity": 1,
"totalSaving": 1.5
}]
*/
When to use map() vs. other methods
Use map()
when:
- You need to create a new array using items from an existing array.
- You need to chain other array methods.
- You want to leave the original array unchanged.
Consider using other methods when:
- You don't need to create a new array (use
forEach()
). - You need to accumulate a value (use
reduce()
). - You need to find a specific element or index position (use
find()
orfindIndex()
). - You need to filter elements (use
filter()
).
Conclusion
The map()
method provides a way to transform arrays without modifying the original data. By returning a new array with the transformed values, map()
enables powerful data transformations and is ideal for creating new representations of your data.