It combines all elements of an array into a single value using a callback (reducer) and an initial value. The callback receives an accumulator and each element, and returns the next accumulator. reduce returns the final accumulator.
reduce in JavaScript: Examples and Use Cases
What does reduce do in JavaScript?
The answer
More FAQs in reduce in JavaScript: Examples and Use Cases
Use an object as the initial value. For each element, add it to the array at acc[property]: people.reduce((acc, p) => { (acc[p.city] ||= []).push(p); return acc; }, {}).
Use an object as the initial value. For each element, increment the count: arr.reduce((acc, char) => { acc[char] = (acc[char] || 0) + 1; return acc; }, {}).
To avoid bugs with empty arrays (TypeError: Reduce of empty array with no initial value) and type mismatches (when the accumulator type differs from the element type, like building an object from an array of objects).
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.