Sub topic 6
Grouping into a Map with Map.groupBy
This chapter assumes you already know how Object.groupBy works and are comfortable with basic Map methods such as get, has, and size. Map.groupBy takes the same arguments as Object.groupBy. The difference is what you get back: a Map instead of a plain object.
The Same Call, a Different Container
Map.groupBy(items, callback) walks the iterable and calls callback(element, index) once per element. Elements whose callbacks return the same key end up in one array, and that array is stored in the Map under that key.
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 byType = Map.groupBy(inventory, ({ type }) => type);
console.log(byType instanceof Map); // true
console.log(byType.size); // 3
console.log(byType.get("fruit").map((item) => item.name)); // ["bananas", "cherries"]
console.log(byType.has("dairy")); // false
console.log(byType.get("dairy")); // undefinedYou read groups with Map methods, not with dot or bracket access. byType.fruit is undefined because groups are Map entries, not object properties.
Keys Keep Their Type
A Map stores keys as they are, so the value your callback returns is the exact key you look up later. If the callback returns a boolean, you get a boolean key back. It is not turned into the string "true".
const scores = [42, 91, 67, 88, 30];
const byPass = Map.groupBy(scores, (score) => score >= 60);
console.log([...byPass.keys()]); // [false, true]
console.log(byPass.get(true)); // [91, 67, 88]
console.log(byPass.get("true")); // undefinedThe last line is a common mistake. A lookup has to use the same type the callback returned. The next chapter covers what that means when keys are objects.
Iterating Over Groups
A Map iterates in insertion order. Each key is inserted the first time the callback returns it. You can loop over entries directly without calling Object.entries:
const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
const byLetter = Map.groupBy(words, (word) => word[0]);
for (const [letter, group] of byLetter) {
console.log(`${letter}: ${group.join(", ")}`);
}
// a: apple, avocado
// b: banana, blueberry
// c: cherrybyLetter.forEach((group, letter) => ...), [...byLetter.values()], and Array.from(byLetter) also work.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Reading `result.key` or `result["key"]` | Always `undefined` | Use `result.get(key)` |
| Looking up `"1"` when the callback returned `1` | `undefined` | Look up with the same type the callback returned |
| Calling `inventory.groupBy(...)` | `TypeError: ... is not a function` | Call the static `Map.groupBy(inventory, ...)` |
| Passing `JSON.stringify` the Map | Prints `{}` | Convert first: `Object.fromEntries(result)` |
Exercise
Given const nums = [3, 8, 12, 5, 20];, write a Map.groupBy call that groups the numbers by whether they are greater than 6, and then log the array of numbers that are greater than 6. What does it print?
Show answer
const big = Map.groupBy(nums, (n) => n > 6); console.log(big.get(true)); prints [8, 12, 20]. The keys are the booleans true and false, so big.get("true") would return undefined.
Exercise
For const g = Map.groupBy(["x", "yy", "z"], (s) => s.length);, what do g.size, g.get(1), and g.get("1") return?
Show answer
g.size is 2, g.get(1) is ["x", "z"], and g.get("1") is undefined. The keys are the numbers 1 and 2, and a Map does not convert them to strings.