JavaScript group an array of objects by key
2 min readApr 17, 2019
In this article, I will explain about the groupBy array of object in javascript.
I will explain this using one example.
const cars = [{
make: "audi",
model: "r8",
year: "2012"
},
{
make: "audi",
model: "rs5",
year: "2013"
},
{
make: "ford",
model: "mustang",
year: "2012"
},
{
make: "ford",
model: "fusion",
year: "2015"
},
{
make: "kia",
model: "optima",
year: "2012"
}];
Now I am going group using make. For example ‘make:’audi’’ to ‘audi: {[…..]}’. We use to reduce function.
Reduce
The
reduce()
method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
let group = cars.reduce((r, a) => {
console.log("a", a);
console.log('r', r);
r[a.make] = [...r[a.make] || [], a];
return r;
}, {});
console.log("group", group);
The output should be like this.
Another way:
Using lodash we can write simply.
lodash.groupBy(cars, 'make')
We can get the same output.