Reduce
π¨βπΌ The
reduce method accumulates an array into a single value. It's the most
powerful (and sometimes confusing) array methodβand a cornerstone of functional
programming.const numbers = [1, 2, 3, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0)
// 10
Parameters:
- accumulator (
acc) - The running total - current (
n) - The current element - initial value (
0) - Starting point
- Use
reduceto sum all prices - Use
reduceto find the most expensive product - Use
reduceto count products by category
π° Reduce syntax:
const result = array.reduce((accumulator, current) => newAccumulator, initial)
π° Counting by category (immutable pattern using spread):
const counts = products.reduce(
(acc, p) => ({
...acc,
[p.category]: (acc[p.category] || 0) + 1,
}),
{} as Record<string, number>,
)
Each iteration returns a new object instead of mutating the accumulator. This
is the functional approachβeasier to reason about and debug.