Facebook Pixel

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

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

Verify This Answer

Cross-check this information using these trusted sources:

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?

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.