Sub topic 6
Grouping into a Map with Map.groupBy
Object.groupBy puts its groups in a plain object, so every key becomes a string or a symbol. Map.groupBy takes the same two arguments, an iterable and a key callback, but returns a Map. A Map stores each key exactly as your callback returned it. A number stays a number, a boolean stays a boolean, and an object stays that same object.
This chapter covers the basic mechanics: calling Map.groupBy, reading the groups back with Map methods, and the mistakes people make when they treat a Map like a plain object. It assumes you know how Map works (get, set, has, size, and iteration) and that you have already used Object.groupBy and its key callback.
The Shape of a Map.groupBy Call
The signature matches Object.groupBy:
Map.groupBy(items, callbackFn)itemsis any iterable: an array, a string, aSet, a generator, and so on.callbackFn(element, index)runs once for each element and returns that element's key.- The return value is a new
Map. Each key maps to an array of the elements that produced it.
Here is the inventory example from earlier chapters, grouped into a Map:
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.keys()]); // ["vegetables", "fruit", "meat"]
console.log(byType.get("fruit").map((item) => item.name)); // ["bananas", "cherries"]With string keys, the grouping is the same as Object.groupBy. Only the container is different, so you read groups through get instead of property access.
What Happens Inside
The algorithm walks the iterable once. For each element it calls your callback, takes the returned key, and appends the element to that key's array. It creates the array the first time it sees the key. Because a Map remembers insertion order, the keys come out in the order each one first appeared in the input.
Two details come straight from this loop:
- The callback runs synchronously, in iteration order, exactly once per element. If it throws, the whole call throws and you get no partial
Map. - The key is used as-is. Nothing converts it to a string, and it is matched against existing keys the way
Map.prototype.getmatches them. The next chapter covers that comparison rule, SameValueZero, and object keys.
Non-String Keys Stay Non-String
Since the key is never converted, numeric keys stay numbers. That matters when you look them up:
const scores = [72, 95, 88, 54, 100, 61];
const byBand = Map.groupBy(scores, (s) => Math.floor(s / 10) * 10);
console.log([...byBand.keys()]); // [70, 90, 80, 50, 100, 60]
console.log(byBand.get(90)); // [95]
console.log(byBand.get("90")); // undefinedget("90") returns undefined because the string "90" and the number 90 are different Map keys. With Object.groupBy both would be the same property. Here the key type you return is the key type you have to look up with.
The keys also come out in first-seen order (70, 90, 80, ...) and are not sorted. Sort them yourself if you need sorted output:
const scores = [72, 95, 88, 54, 100, 61];
const byBand = Map.groupBy(scores, (s) => Math.floor(s / 10) * 10);
const sorted = [...byBand.keys()].sort((a, b) => a - b);
console.log(sorted); // [50, 60, 70, 80, 90, 100]The index argument works the same way it does with Object.groupBy. Here it deals tasks out to two workers in turn, using the numbers 0 and 1 as keys:
const tasks = ["write", "test", "review", "deploy", "monitor"];
const byWorker = Map.groupBy(tasks, (_, i) => i % 2);
console.log(byWorker.get(0)); // ["write", "review", "monitor"]
console.log(byWorker.get(1)); // ["test", "deploy"]Reading Groups Back
The result is an ordinary Map with the normal Map.prototype, so every Map method is available. It does not have the null-prototype quirks of Object.groupBy's result.
| Task | Map code | Notes |
|---|---|---|
| Get one group | `map.get(key)` | Returns `undefined` if no element produced `key` |
| Get a group or an empty array | `map.get(key) ?? []` | Safe to call `.length` or `.map` on |
| Check whether a group exists | `map.has(key)` | Uses the same key matching as `get` |
| Count the groups | `map.size` | A property, not a method |
| List the keys | `[...map.keys()]` | In first-seen order |
| Loop over the groups | `for (const [key, items] of map)` | Entries in first-seen order |
Looping is the most common pattern:
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);
for (const [type, items] of byType) {
console.log(`${type}: ${items.length}`);
}
// vegetables: 1
// fruit: 2
// meat: 1
console.log(byType.has("dairy")); // false
console.log((byType.get("dairy") ?? []).length); // 0The Map and its arrays belong to you. You can set, delete, or push onto a group afterward, and nothing reruns the grouping.
Common Errors
Treating the Map like an object
Property access does not read Map entries. This mistake fails silently:
const byType = Map.groupBy(["apple", "avocado", "beet"], (w) => w[0]);
console.log(byType.a); // undefined
console.log(byType["a"]); // undefined
console.log(byType.get("a")); // ["apple", "avocado"]If you port code from Object.groupBy to Map.groupBy, search for every dot or bracket lookup on the result and change it to get.
Serializing a Map with JSON.stringify
JSON.stringify only reads an object's own enumerable properties, and a Map keeps its entries somewhere else. You get an empty object:
const byType = Map.groupBy(["apple", "avocado", "beet"], (w) => w[0]);
console.log(JSON.stringify(byType)); // "{}"
console.log(JSON.stringify(Object.fromEntries(byType))); // "{\"a\":[\"apple\",\"avocado\"],\"b\":[\"beet\"]}"
console.log(JSON.stringify([...byType])); // "[[\"a\",[\"apple\",\"avocado\"]],[\"b\",[\"beet\"]]]"Object.fromEntries gives a readable object, but it turns every key into a string. If your keys are objects or you need to tell 1 from "1", serialize the entries array instead.
Forgetting to return from a block-body callback
An arrow function with braces needs an explicit return. Without one, every element gets the key undefined, and Map is happy to store that:
const inventory = [
{ name: "bananas", type: "fruit" },
{ name: "goat", type: "meat" },
];
const broken = Map.groupBy(inventory, (item) => {
item.type;
});
console.log(broken.size); // 1
console.log([...broken.keys()]); // [undefined]
console.log(broken.get(undefined).length); // 2With Object.groupBy the same bug produces a group named "undefined". In both cases nothing throws. If size comes out as 1 when you expected more, check the callback first.
Passing something that is not iterable
A plain object is not iterable, so Map.groupBy({ a: 1 }, fn) throws a TypeError. A non-function callback throws a TypeError too. To group an object's values, pass Object.values(obj). To group its entries, pass Object.entries(obj).
const stock = { apples: 4, pears: 0, plums: 9 };
const byAvailability = Map.groupBy(Object.entries(stock), ([, qty]) => qty > 0);
console.log(byAvailability.get(true)); // [["apples", 4], ["plums", 9]]
console.log(byAvailability.get(false)); // [["pears", 0]]In this example the keys are the booleans true and false, not the strings "true" and "false".
Exercises
Exercise
Given const words = ["hi", "hey", "hello", "yo"], write a Map.groupBy call that groups the words by length. What do result.get(2) and result.get("2") return, and what is [...result.keys()]?
Show answer
const result = Map.groupBy(words, (w) => w.length); result.get(2) returns ["hi", "yo"]. result.get("2") returns undefined, because the keys are numbers and a Map does not treat "2" as equal to 2. [...result.keys()] is [2, 3, 5], the order in which each length first appeared.
Exercise
A teammate switched from Object.groupBy to Map.groupBy and now sends JSON.stringify(groups) to the server. The server receives "{}", and the template code groups.admin?.length always shows nothing. Explain both bugs and fix them.
Show answer
JSON.stringify ignores Map entries because they are not own enumerable properties, so it produces "{}". Fix it with JSON.stringify(Object.fromEntries(groups)) when the keys are strings, or JSON.stringify([...groups]) to keep non-string keys. groups.admin reads a property on the Map object, not an entry, so it is always undefined. Fix it with groups.get("admin")?.length ?? 0.
Exercise
Why does Map.groupBy([1, 2, 3], (n) => { n > 1 ? "big" : "small"; }) produce a Map of size 1, and what is its single key?
Show answer
The arrow function has a block body with no return statement, so it returns undefined for every element. Map.groupBy stores undefined as a real key, so all three numbers go into one group under the key undefined. Add return, or drop the braces, to fix it.