const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, n) => acc + n, 0);
// sum: 10
const grouped = ['a', 'b', 'a'].reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
// grouped: { a: 2, b: 1 }- Signature: arr.reduce((accumulator, current, index, array) => newAcc, initialValue)
- ALWAYS pass an initial value to avoid subtle bugs on empty arrays
- Powerful enough to implement map/filter/sum/groupBy yourself
Tip
Be ready to whiteboard 'implement map using reduce' — a very common follow-up.