Follow @endyourif rss Facebook LinkedIn

Group an array of objects by key with Javascript Group an array of objects by key with Javascript

Published on Jun 19, 2022

I feel so privileged being able to use Linq group by statements when I'm working in C# to quickly and easily group a list of objects; however, when it comes to Javascript, it's not quite so easy. Let's solve that today by creating a new groupBy Array prototype function that leverages the reduce function.



The reduce function works by iterating through the array for us, but really importantly it also passes the resulting value from the previously executed iteration. This will allow us to dynamically build up our list of keys.

Let's begin by looking at example array that I want to leverage this new groupBy function with.


var cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2022'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2023'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2022'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2021'
}, {
'make': 'kia',
'model': 'optima',
'year': '2021'
},
];


Now, I want the output array to be group the cars up by the make, e.g.


var cars = {
'audi': [
{
'model': 'r8',
'year': '2022'
}, {
'model': 'rs5',
'year': '2023'
},
],

'ford': [
{
'model': 'mustang',
'year': '2022'
}, {
'model': 'fusion',
'year': '2021'
}
],

'kia': [
{
'model': 'optima',
'year': '2021'
}
]
};


And finally to accomplish this I will create a new Array prototype function called groupBy that uses the reduce function to iterate the array and build up a new array grouped by the car make value:


Array.prototype.groupBy = function(key) {
return this
.reduce((hash, obj) => {
if(obj[key] === undefined) return hash;
return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
}, {})
};


To use this function with the previously created cars variable:
console.log(cars.groupBy('make'));

Tags: JavaScript | Javascript Arrays Tutorial | groupby

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP