What is Array.reduce() and how does it work?
reduce boils an array down to a single value by running a function across all elements, carrying an accumulator along the way.
Accumulator — the running result passed from one iteration to the next.
Current value — the element being processed.
Initial value — the accumulator's starting point; always provide one to avoid edge-case bugs on empty arrays.
Versatile: reduce can sum, flatten, group, or count — many other array methods can be built from it.
const numbers = [1, 2, 3, 4, 5];
// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
// Max
const max = numbers.reduce((a, b) => Math.max(a, b), -Infinity); // 5
// Group by
const people = [
{ name: 'Alice', dept: 'Eng' },
{ name: 'Bob', dept: 'Sales' },
{ name: 'Charlie', dept: 'Eng' }
];
const byDept = people.reduce((groups, person) => {
const key = person.dept;
groups[key] = groups[key] || [];
groups[key].push(person);
return groups;
}, {}); // { Eng: [Alice, Charlie], Sales: [Bob] }
// Flatten
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], []); // [1,2,3,4,5]
// Count occurrences
const words = ['yes', 'no', 'yes', 'yes', 'no'];
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {}); // { yes: 3, no: 2 }
// Pipe/compose functions
const pipe = (...fns) => (x) => fns.reduce((v, fn) => fn(v), x);
const transform = pipe(double, addOne, square);reduce starts with an initial value (0, {}, []) and processes each element. Sum adds each number to the accumulator. GroupBy builds an object keyed by department.
Flatten concatenates inner arrays. Count builds a frequency map. Pipe chains functions left-to-right. reduce is the Swiss Army knife of array methods.
Show 3+ use cases: sum (basic), groupBy (practical), and pipe (advanced). Always provide initialValue. reduce can replace map, filter, and flat — but use the specific methods for readability.
The pipe/compose function using reduce is an impressive demo.