reduce() is a JavaScript array method that turns an array into one final value.
That final value can be:
- a number
- an object
- a new array
- a string
Basic syntax:
array.reduce((accumulator, currentItem) => {
return updatedAccumulator;
}, initialValue);
-
accumulator: stores the result while looping -
currentItem: the current array item -
initialValue: the starting value
1. Add numbers together
const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => {
return sum + price;
}, 0);
console.log(total); // 60
How it works:
0 + 10 = 10
10 + 20 = 30
30 + 30 = 60
2. Use reduce() inside React
A common use case is calculating a shopping cart total.
function Cart() {
const cartItems = [
{ id: 1, name: "Phone", price: 500 },
{ id: 2, name: "Case", price: 20 },
{ id: 3, name: "Charger", price: 30 },
];
const totalPrice = cartItems.reduce((total, item) => {
return total + item.price;
}, 0);
return (
<div>
<h2>Cart Total: ${totalPrice}</h2>
</div>
);
}
React does not have a special version of reduce(). You use the normal JavaScript reduce() method inside your component.
3. Calculate quantity × price
const cartItems = [
{ name: "T-shirt", price: 20, quantity: 2 },
{ name: "Shoes", price: 50, quantity: 1 },
];
const total = cartItems.reduce((sum, item) => {
return sum + item.price * item.quantity;
}, 0);
console.log(total); // 90
Calculation:
T-shirts: 20 × 2 = 40
Shoes: 50 × 1 = 50
Total: 90
4. Count items by category
const products = [
{ name: "Phone", category: "electronics" },
{ name: "Laptop", category: "electronics" },
{ name: "Shirt", category: "clothing" },
];
const categoryCounts = products.reduce((counts, product) => {
const category = product.category;
counts[category] = (counts[category] || 0) + 1;
return counts;
}, {});
console.log(categoryCounts);
Result:
{
electronics: 2,
clothing: 1
}
This is useful for dashboards, filters, and statistics.
5. Group items
const users = [
{ name: "Ali", role: "admin" },
{ name: "Sara", role: "user" },
{ name: "Omar", role: "admin" },
];
const usersByRole = users.reduce((groups, user) => {
if (!groups[user.role]) {
groups[user.role] = [];
}
groups[user.role].push(user);
return groups;
}, {});
console.log(usersByRole);
Result:
{
admin: [
{ name: "Ali", role: "admin" },
{ name: "Omar", role: "admin" }
],
user: [
{ name: "Sara", role: "user" }
]
}
6. Create an object from an array
const users = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Sara" },
];
const usersById = users.reduce((result, user) => {
result[user.id] = user;
return result;
}, {});
console.log(usersById);
Result:
{
1: { id: 1, name: "Ali" },
2: { id: 2, name: "Sara" }
}
Now you can quickly find a user:
console.log(usersById[2].name); // Sara
When should you use reduce()?
Use reduce() when you want to turn an array into one result.
Good use cases:
- calculate a total
- count items
- group items
- build an object
- combine values
Do not use reduce() when map(), filter(), or find() is clearer.
// Use map to transform every item
const names = users.map((user) => user.name);
// Use filter to keep some items
const admins = users.filter((user) => user.role === "admin");
// Use find to get one item
const user = users.find((user) => user.id === 2);
A simple rule:
Use
reduce()when the final result is different from the original array structure.
Credits: ChatGPT
Top comments (0)