Intermediate · 12 min
Reduce and group data
Use an explicit initial accumulator to calculate totals and counts.
Choose an initial value
reduce() combines items into one result. Providing an initial value also defines the result for an empty array.
const prices = [4, 6, 3];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
console.log([].reduce((sum, value) => sum + value, 0));Output
13 0
Count repeated values
An accumulator can be an object or Map. A Map avoids treating arbitrary input strings as object property names.
const counts = ["tea", "coffee", "tea"].reduce((map, name) => {
map.set(name, (map.get(name) ?? 0) + 1);
return map;
}, new Map());
console.log(counts.get("tea"));Output
2
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Total quantities
Use reduce() to add the quantity of every item. Set total and display it.
Add item.quantity to the accumulator.