Array Methods: reduce, every, some
reduce is the most powerful array method — it 'reduces' an array to a single value. It can do everything map, filter, and forEach do, but its primary use is aggregation: sums, counts, grouping, and flattening.
reduce Explained
- reduce(callback, initialValue) — Reduces array to single value: sum, count, object, string, etc.
- callback(accumulator, currentValue, index, array) — accumulator holds the running result
- initialValue — Starting value for accumulator. Always provide it! (avoids bugs)
- Use cases — Sum, average, max/min, count occurrences, group by property, flatten arrays
- Don't overuse — If map + filter do the job, prefer them. reduce is for aggregation
reduce Code
const numbers = [1, 2, 3, 4, 5];
// Sum
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
// Product
const product = numbers.reduce((acc, num) => acc * num, 1);
console.log(product); // 120
// Max value
const max = numbers.reduce((max, num) => num > max ? num : max, -Infinity);
console.log(max); // 5
// Count occurrences
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // { apple: 3, banana: 2, cherry: 1 }
// Group by property
const people = [
{ name: "Alice", dept: "Engineering" },
{ name: "Bob", dept: "Marketing" },
{ name: "Charlie", dept: "Engineering" },
];
const byDept = people.reduce((groups, person) => {
const dept = person.dept;
groups[dept] = groups[dept] || [];
groups[dept].push(person.name);
return groups;
}, {});
console.log(byDept);
// { Engineering: ["Alice", "Charlie"], Marketing: ["Bob"] }
// Real-world: cart total
const cart = [
{ item: "Laptop", price: 999, qty: 1 },
{ item: "Mouse", price: 29, qty: 2 },
{ item: "Keyboard", price: 79, qty: 1 },
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
console.log("Cart total: ₹" + total); // ₹1136Tip
Tip
Use reduce for grouping data by a property: array.reduce((groups, item) => { groups[item.category] = [...(groups[item.category] || []), item]; return groups; }, {}). This is one of the most powerful real-world patterns.
Set methods coming in ES2025! Until then, use spread + filter. Sets for unique values. O(1) has() lookup.
Common Mistake
Warning
Calling reduce without an initialValue on an empty array throws TypeError. Always provide the second argument: reduce(callback, 0) for sums, reduce(callback, []) for arrays, reduce(callback, {}) for objects.
Practice Task
Note
Master reduce: (1) Sum the prices in a cart array of objects. (2) Count how many times each word appears in an array. (3) Group an array of students by their grade level. (4) Find the average age from a user array.
Quick Quiz
Key Takeaways
- reduce is the most powerful array method — it 'reduces' an array to a single value.
- reduce(callback, initialValue) — Reduces array to single value: sum, count, object, string, etc.
- callback(accumulator, currentValue, index, array) — accumulator holds the running result
- initialValue — Starting value for accumulator. Always provide it! (avoids bugs)