Chapter VIII · Arrays
reduce
The reduce method executes a reducer callback function over each array element, accumulating them into a single summary value.
01 How It Works
Think of counting loose coins into a piggy bank to find the total sum.
An accumulator carries the running total across each iteration step.
example.js
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0); // 10
1. Call .reduce() with a callback and initial accumulator value.
2. Add or aggregate each current item into the accumulator.
3. Return the final single accumulated result.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const values = [5, 10, 15];
const total = values.reduce((acc, val) => acc + val, 0);
Key Takeaway
Reduce aggregates complex arrays down into a single consolidated output value.