First we define an array containing objects representing an inventory of different foodstuffs. Each food has a type
and a quantity
.
const inventory = [
{ 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 },
];
The code below groups the elements by the value of their type
property.
const result = Object.groupBy(inventory, ({ type }) => type);
/* Result is:
{
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 }
]
}
*/
The arrow function just returns the type
of each array element each time it is called. Note that the function argument { type }
is a basic example of object destructuring syntax for function arguments. This unpacks the type
property of an object passed as a parameter, and assigns it to a variable named type
in the body of the function. This is a very succinct way to access the relevant values of elements within a function.
We can also create groups inferred from values in one or more properties of the elements. Below is a very similar example that puts the items into ok
or restock
groups based on the value of the quantity
field.
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = Object.groupBy(inventory, myCallback);
/* Result is:
{
restock: [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
ok: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/