Most of the time we use some third party library like underscore or lodash, to group an array of objects based on some property.
But did you know that we can also do this directly with JavaScript, since the JavaScript has a special method called .groupBy().
groupBy() is a static method on Javascript 'Object'.
Lets take an example-
const products = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
In above products data, if you want to group data by it's type, then we can use groupBy() as shown below
Object.groupBy(products, item => item.type)
Output:
{
"vegetables": [
{
"name": "asparagus",
"type": "vegetables",
"quantity": 5
}
],
"fruit": [
{
"name": "bananas",
"type": "fruit",
"quantity": 0
},
{
"name": "cherries",
"type": "fruit",
"quantity": 5
}
],
"meat": [
{
"name": "goat",
"type": "meat",
"quantity": 23
},
{
"name": "fish",
"type": "meat",
"quantity": 22
}
]
}
Top comments (0)