Here are some excellent use cases for .map() and .reduce() in JavaScript:
.map()
- Transforming data:
.map()is often used to transform data in an array by applying a function to each element and returning a new array with the transformed values. For example, you could use.map()to convert an array of Celsius temperatures to an array of Fahrenheit temperatures:
javascript
const celsiusTemperatures = [0, 20, 30, 40, 50]; const fahrenheitTemperatures = celsiusTemperatures.map(celsius => (celsius * 9/5) + 32); console.log(fahrenheitTemperatures); // [32, 68, 86, 104, 122]- Creating new objects:
.map()can also be used to create new objects from an array of values. For example, you could use.map()to create an array of objects representing products with their prices:
const products = ['apple', 'banana', 'orange'];
const prices = [0.5, 0.25, 0.75];
const productObjects = products.map((product, index) => ({ name: product, price: prices[index] }));
console.log(productObjects); // [{ name: 'apple', price: 0.5 }, { name: 'banana', price: 0.25 }, { name: 'orange', price: 0.75 }].reduce()
- Summing values:
.reduce()is often used to calculate the sum of values in an array. For example, you could use.reduce()to calculate the total cost of items in a shopping cart:
const cart = [
{ name: 'apple', price: 0.5, quantity: 2 },
{ name: 'banana', price: 0.25, quantity: 3 },
{ name: 'orange', price: 0.75, quantity: 1 }
];
const totalCost = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
console.log(totalCost); // 2.25- Grouping values:
.reduce()can also be used to group values in an array by a common property. For example, you could use.reduce()to group an array of objects representing people by their age:
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 },
{ name: 'Dave', age: 30 }
];
const ageGroups = people.reduce((groups, person) => {
if (!groups[person.age]) {
groups[person.age] = [];
}
groups[person.age].push(person);
return groups;
}, {});
console.log(ageGroups);
/*
{
25: [
{ name: 'Alice', age: 25 },
{ name: 'Charlie', age: 25 }
],
30: [
{ name: 'Bob', age: 30 },
{ name: 'Dave', age: 30 }
]
}
*/
These are just a few examples of the many use cases for .map() and .reduce() in JavaScript. These methods are very powerful and can be used in a variety of ways to manipulate and transform data.