AI Hints
Home›JavaScript Tutorial›map, filter, reduce
JavaScript · Lesson 51 of 138

reduce

Combine into one.

⏱ 2 min read▶ Video at 1:02:10🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Add up a list of prices. Find the biggest number. Count how many times each word appears. Each of these combines a whole array into one value. That's what reduce does.

reduce
From the video: reduce
  • Add up, find the biggest, count
  • Many values into one
  • reduce

An accumulator

Reduce takes a callback and a starting value. The callback gets the running result, called the accumulator, and the current item, and returns the new running result. Here we start at zero, and add each price. Then we use reduce to count fruit. Run it.

app.jsjavascript
const prices = [4, 10, 6];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log("total:", total);

const basket = ["apple", "pear", "apple", "fig", "apple"];
const counts = basket.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(counts);
Output
total: 20
{ apple: 3, pear: 1, fig: 1 }

Always give a start value

Always pass the starting value, the second argument to reduce. Without it, reduce uses the first item as the start, which breaks on empty arrays. Reduce is powerful, but it can be hard to read. For simple jobs, like a sum, it's perfect. For complicated ones, a loop can be clearer.

keyvalue
reduce(fn, start)combine into one
fn(acc, item)returns the new acc
Start valuealways pass it
Clear codesometimes a loop is better

Summary

Reduce combines an array into a single value, using an accumulator. Always give it a starting value. Next, chaining map, filter, and reduce.

Key takeaways
  • reduce((acc, x) => ..., start)
  • Sums and counts
  • Pass a start value
Next up: Chaining Methods — map, filter, reduce together