Collapse to One Value
reduce combines all elements into a single result.
You control the accumulator and how it updates each step.
JavaScript Tutorial
reduce turns an array into a single value like a sum, object, or combined list.
It is powerful but should be used with care for readability.
Many tasks require aggregating data. reduce handles those in one pass.
It is a key tool for data transformation pipelines.
array.reduce((acc, value, index, array) => newAcc, initialValue)const nums = [1, 2, 3];
const total = nums.reduce((sum, n) => sum + n, 0);
console.log(total);Accumulate a sum with an initial value.
const items = ["a", "b"];
const counts = items.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
console.log(counts);Use reduce to build objects from arrays.
reduce combines all elements into a single result.
You control the accumulator and how it updates each step.
Always provide an initial value to avoid edge cases on empty arrays.
The initial value sets the type of your accumulator.
reduce can build objects, group data, or flatten arrays.
It is powerful but should stay readable.
const users = [{ role: "admin" }, { role: "user" }];
const grouped = users.reduce((acc, u) => {
(acc[u.role] ||= []).push(u);
return acc;
}, {});
console.log(grouped);Group array items into buckets.
const nested = [[1, 2], [3]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log(flat);Reduce can flatten one level.
Without
let total = 0;
for (const n of nums) {
total += n;
}With
const total = nums.reduce((sum, n) => sum + n, 0);Provide an initial value to avoid surprises on empty arrays.
Keep reducer logic readable or split into helpers.
Work with the accumulator instead of globals.
The running result that reduce updates each iteration.
It defines the accumulator type and handles empty arrays.
When map or filter is clearer.
Practice: Use reduce to calculate the total price of a cart.
const cart = [10, 15, 5];
// TODO: total price
One Possible Solution
const cart = [10, 15, 5];
const total = cart.reduce((sum, n) => sum + n, 0);
console.log(total);A single value produced by the reducer.
It prevents errors and controls accumulator type.
Yes, but it may reduce readability.
Try changing the array to see the accumulator update.