Group objects from array in JavaScript
I recently came across a scenario, where I needed to group different objects depending on a specific type from an array. And it is not the first time I have faced this problem. And as for as I know, there are no built in function that does this for us, except for Array.group that is only supported by Safari browsers..
In this guide, we will show how we can create our own group function and solve it ourselves!
Our example
Let's consider we have the following array:
const cars = [ { type: "electric", brand: "Tesla", }, { type: "electric", brand: "Volvo", }, { type: "electric", brand: "Kia", }, { type: "combustion", brand: "Ford", }, { type: "combustion", brand: "Dacia", }, { type: "combustion", brand: "Renault", }, { type: "electric", brand: "Volkswagen", }, ];
So, we have a lot of cars in our array. We have two differen types of engines, electric and combustion. Instead of having them in an array, we want to have them grouped in an object.
Implementation
The implementation is fairly simple, we will use the reduce() function to add each element to our new object.
export const groupBy = (array, key) => array.reduce((finalObject, currentObject) => { (finalObject[currentObject[key]] = finalObject[currentObject[key]] || []).push(currentObject); return finalObject; }, {});
There we go. So our function will take an array and the key of the property that we want to group them by.
Let's try it:
console.log(groupBy(cars, "type"));
Result:
{ "electric": [ { "type": "electric", "brand": "Tesla" }, { "type": "electric", "brand": "Volvo" }, { "type": "electric", "brand": "Kia" }, { "type": "electric", "brand": "Volkswagen" } ], "combustion": [ { "type": "combustion", "brand": "Ford" }, { "type": "combustion", "brand": "Dacia" }, { "type": "combustion", "brand": "Renault" } ] }
And voila. Now we have an object that is grouped by the two types and we can easier access the right objects in our application.
Outro
This was a short example. But, speaking of experience, this small utilities are so great to have nearby because they make our life easier. And we (speaking for my myself) tend to forget how the correct implementation is so it is always great to have them close by to save some precious time, instead of having to re-implement them all the time.
I hope you found this short tutorial helpful, and good luck with your project!