Reduce
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
π¨ Open
and:
- Use
reduceto sum all prices - Use
reduceto find the most expensive product - Use
reduceto count products by category
π°
reduce combines all items into one accumulated result.Each iteration returns a new object instead of mutating the accumulator. This
is the functional approachβeasier to reason about and debug.