Sub topic 2
Grouping into a Map with Map.groupBy
This chapter assumes you already know how Object.groupBy and its key callback work, and that you have basic experience with Map.
Grouping into a Map with Map.groupBy
Map.groupBy takes the same arguments as Object.groupBy: an iterable and a callback that returns a key for each element. The difference is the return value. It returns a Map, so you read groups with get, has, and keys instead of property access.
Using Objects and Other Non-String Values as Keys
A Map stores each key as the value the callback returned, without converting it. You can group by an object, but you must look the group up with the same object reference. Map keys are compared with SameValueZero, which checks identity for objects. Two objects that look the same are still different keys.
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 },
];
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient
);
console.log(result.get(restock).length); // 3
console.log(result.get(sufficient)[0].name); // "goat"
console.log(result.get({ restock: true })); // undefinedHow Object.groupBy Converts Keys to Strings
Object.groupBy stores groups as object properties. Any key that is not a symbol gets converted to a string. If your callback returns a boolean, the groups come out as "true" and "false":
const isEven = (n) => n % 2 === 0;
const asObject = Object.groupBy([1, 2, 3, 4], isEven);
console.log(Object.keys(asObject)); // ["false", "true"]
const asMap = Map.groupBy([1, 2, 3, 4], isEven);
console.log([...asMap.keys()]); // [false, true]
console.log(asMap.get(true)); // [2, 4]The conversion also merges keys. 1 and "1" end up in the same group, and every object key becomes "[object Object]".
Choosing Between Object.groupBy and Map.groupBy
| Situation | Use |
|---|---|
| Keys are strings, and you want dot access or JSON output | `Object.groupBy` |
| Keys are objects, booleans, or numbers whose type matters | `Map.groupBy` |
| You need keys to stay in insertion order | `Map.groupBy` |
| You will pass the result to `Object.entries` or a template | `Object.groupBy` |
Exercise
You group users with Object.groupBy(users, (u) => u.teamObject), where teamObject is a different object for each team. How many groups do you get, and which method should you use instead?
Show answer
You get one group, keyed "[object Object]", because every object key is converted to the same string. Use Map.groupBy and look up each group with the original team object reference.