Facebook Pixel
reduce in JavaScript: Examples and Use Cases

How do you group an array of objects by a property with reduce in JavaScript?

The answer

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; }, {}).

More FAQs in reduce in JavaScript: Examples and Use Cases

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.

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.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.