🧠 What is .reduce()
?
.reduce()
is a method that reduces an array to a single value by applying a function on each element — one at a time — while keeping track of an accumulator.
Let’s see it in action:
🔁 Basic Example: Adding Numbers in an Array
const myNums = [1, 2, 3, 4, 5];
const myTotal = myNums.reduce(function (acc, currVal) {
console.log(`acc: ${acc} and currval: ${currVal}`);
return acc + currVal;
}, 0); // 0 is the initial value of the accumulator
console.log(myTotal);
🧾 Output:
acc: 0 and currval: 1
acc: 1 and currval: 2
acc: 3 and currval: 3
acc: 6 and currval: 4
acc: 10 and currval: 5
15
🔍
acc
keeps track of the total so far, andcurrVal
is the current item from the array.
✅ Arrow Function Version
const NewTotal = myNums.reduce((acc, curr) => acc + curr, 0);
console.log(NewTotal);
✔️ Cleaner and more readable for simple operations.
🛒 Real-Life Use Case: Calculating Total Price in a Cart
Imagine you're building an e-commerce site, and you want to calculate the total price from the cart. Here's how:
const shoppingCart = [
{ itemName: "JS Course", price: 2999 },
{ itemName: "Py Course", price: 999 },
{ itemName: "Mobile dev Course", price: 5999 },
{ itemName: "Data Science Course", price: 12999 },
];
const priceToPay = shoppingCart.reduce((acc, item) => acc + item.price, 0);
console.log(priceToPay); // Output: 22996
🛍️ Instead of manually looping and adding,
reduce()
elegantly combines it all into one line.
📌 Syntax Recap
array.reduce((accumulator, currentValue) => {
// logic
return updatedAccumulator;
}, initialValue);
🔄 .reduce()
vs .map()
or .filter()
Method | Purpose | Returns |
---|---|---|
.map() |
Transforms each item | New array |
.filter() |
Selects items based on condition | New array |
.reduce() |
Combines all items into one result | Single value |
🧠 Final Takeaway
.reduce()
is powerful and versatile — from summing numbers to aggregating complex data. Once you get the hang of it, you’ll start reaching for it every time you need to calculate a total, build a string, or even transform arrays in advanced ways.
Top comments (0)