Array.prototype.reduce()A detailed, beginner-friendly explanation with interactive step-by-step visualization.
reduce does (in one sentence)It iterates over an array and "reduces" it to a single value by running a callback that receives an accumulator and the current value on each step.
const result = array.reduce((accumulator, currentValue, currentIndex, array) => {
// your logic
return accumulator;
}, initialValue);
initialValue if provided).initialValue — avoids subtle bugs (especially with empty arrays).reduce.map or filter instead — they are more readable for common cases.reduce is generic — you can produce numbers, strings, objects, arrays, or even promises (with care).// example code will appear here after running
Array: [10, 20, 30] with initialValue = 0
| Iteration | accumulator (before) | currentValue | accumulator (after return) |
|---|---|---|---|
| 1 | 0 | 10 | 0 + 10 = 10 |
| 2 | 10 | 20 | 10 + 20 = 30 |
| 3 | 30 | 30 | 30 + 30 = 60 |
Final result: 60
const total = nums.reduce((acc, curr) => acc + curr, 0);
const obj = arr.reduce((acc, val) => { acc[val] = (acc[val] || 0) + 1; return acc }, {});
const grouped = items.reduce((acc, item) => { (acc[item.type] ||= []).push(item); return acc }, {});
const flat = arrays.reduce((acc, a) => acc.concat(a), []);
initialValue?If you omit initialValue, the first array element becomes the accumulator and iteration starts from the second element. This can cause errors with empty arrays or when the accumulator must be a different type (object vs number).
// Dangerous when array may be empty
[].reduce((acc, curr) => acc + curr); // throws TypeError: Reduce of empty array with no initial value
// Safer
[].reduce((acc, curr) => acc + curr, 0); // 0