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: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];
The code below uses Map.groupBy()
with an arrow function that returns the object keys named restock
or sufficient
, depending on whether the element has quantity < 6
. The returned result
object is a Map
so we need to call get()
with the key to obtain the array.
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
Note that the function argument { quantity }
is a basic example of object destructuring syntax for function arguments. This unpacks the quantity
property of an object passed as a parameter, and assigns it to a variable named quantity
in the body of the function. This is a very succinct way to access the relevant values of elements within a function.
The key to a Map
can be modified and still used. However you can't recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined