groupBy < Object < JavaScript
The Object groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
// group objects in array by one of the object's properties
const inventoryGroupByType = Object.groupBy(inventory, ({ type }) => type);
console.log(inventoryGroupByType)
{
"fruit":[
{
"name":"cherries",
"quantity":5,
"type":"fruit"
}
],
"meat":[
{
"name":"goat",
"quantity":23,
"type":"meat"
},
{
"name":"fish",
"quantity":22,
"type":"meat"
}
],
"vegetables":[
{
"name":"asparagus",
"quantity":5,
"type":"vegetables"
}
]
}
// another example
function okOrRestock({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const inventoryGroupByRestock = Object.groupBy(inventory, okOrRestock);
console.log(inventoryGroupByRestock)
{
"ok":[
{
"name":"goat",
"quantity":23,
"type":"meat"
},
{
"name":"fish",
"quantity":22,
"type":"meat"
}
],
"restock":[
{
"name":"asparagus",
"quantity":5,
"type":"vegetables"
},
{
"name":"cherries",
"quantity":5,
"type":"fruit"
}
]
}