In this post you’re going to learn how to group an array of objects with the upcoming Array.prototype.group
method.
I recently had the requirement to group an array of objects by a property, and like any good developer - I wanted to explore the upcoming ECMAScript standards to see if anything new had arrived.
It did…
Array.prototype.group
is almost here, now at a Stage 3 in the ECMAScript proposal, and is a superb utility function to easily add a “group by” functionality to your data structures.
Let’s assume the following basic data structure, and take note of the type
property:
const data = [
{ type: 'food', name: 'Pizza' },
{ type: 'drink', name: 'Coffee' },
{ type: 'food', name: 'Hot Dog' }
];
We have two values, 'food'
and 'drink'
. Ideally, we would render them individually, passing to perhaps a separate render function or component.
This would be what we want to create:
const result = {
food: [
{ type: 'food', name: 'Pizza' },
{ type: 'food', name: 'Hot Dog' }
],
drink: [
{ type: 'drink', name: 'Coffee' }
]
}
So, how could we do it? With the addition of the Array.prototype.group
method, it becomes a simple one-liner:
const data = [
{ type: 'food', name: 'Pizza' },
{ type: 'drink', name: 'Coffee' },
{ type: 'food', name: 'Hot Dog' }
];
const result = data.group((item) => item.type);
// ✅ { food: [ { type: 'food', name: 'Pizza' }, { type: 'food', name: 'Hot Dog' } ], drink: [ { type: 'drink', name: 'Coffee' } ] }
console.log(result);
When combined with some object destructuring, things become even more streamlined and elegant:
const data = [
{ type: 'food', name: 'Pizza' },
{ type: 'drink', name: 'Coffee' },
{ type: 'food', name: 'Hot Dog' }
];
const { food, drink } = data.group((item) => item.type);
// ✅ [{ type: 'food', name: 'Pizza' }, { type: 'food', name: 'Hot Dog' }]
console.log(food);
// ✅ [{ type: 'drink', name: 'Coffee' }]
console.log(drink);
Want to go further? Check out my follow-up article on creating your own group by function with reduce! It includes an in-depth ‘build your own’ function that will help you learn what’s happening behind the scenes.
🏆 P.S. check out my latest JavaScript courses if you’re serious about taking your skills to the top.
Thanks for reading, happy grouping!