Sub topic 9
Choosing Between Object.groupBy and Map.groupBy
This chapter assumes you already know how both methods work: Object.groupBy returns a null-prototype object, and Map.groupBy returns a Map whose keys are compared with SameValueZero. You should also know how Object.groupBy converts keys to strings. Here we turn those facts into a decision. When you face a grouping task, which method should you reach for, and what goes wrong if you pick the other one?
Both methods take the same arguments, call the callback once per element, and put elements into new arrays in the same order. They differ only in the container they return, but that container determines how you read the groups, pass them around, and store them.
The Short Rule
Use Object.groupBy when every key is naturally a string and you will read groups by name, destructure them, or serialize them. Use Map.groupBy when keys are objects, when keys of different types must stay distinct, or when you need the groups in exactly the order they were created.
Most real tasks fall clearly on one side. The sections below cover the dimensions that decide the borderline cases.
Dimension 1: What Kind of Key You Have
The key type matters more than anything else. Object.groupBy turns every key into a property key, so any value that is not a symbol becomes a string. For object keys this conversion ruins the result: every plain object becomes the string "[object Object]", and all elements end up in one group.
const ana = { name: "Ana" };
const ben = { name: "Ben" };
const orders = [
{ id: 1, customer: ana },
{ id: 2, customer: ben },
{ id: 3, customer: ana },
];
const wrong = Object.groupBy(orders, (o) => o.customer);
console.log(Object.keys(wrong)); // ["[object Object]"]
console.log(wrong["[object Object]"].length); // 3
const right = Map.groupBy(orders, (o) => o.customer);
for (const [customer, list] of right) {
console.log(customer.name, list.length);
}
// Ana 2
// Ben 1No error is thrown, so the bug can go unnoticed until someone looks at the data. If your callback returns an object, use Map.groupBy.
Mixed primitive types are less obvious. If the callback can return both 1 and "1", Object.groupBy merges them into one group. Map.groupBy keeps them apart.
const values = [1, "1", 2];
const obj = Object.groupBy(values, (v) => v);
console.log(obj["1"]); // [1, "1"]
const map = Map.groupBy(values, (v) => v);
console.log(map.get(1)); // [1]
console.log(map.get("1")); // ["1"]If you want the merge, for example because IDs arrive as both numbers and strings from different sources, Object.groupBy gives it to you for free. If the merge would be a bug, use a Map.
Dimension 2: How You Read the Groups
An object lets you use plain property access and destructuring, which reads well when the set of keys is known ahead of time:
const tasks = [
{ title: "Write tests", status: "done" },
{ title: "Fix bug", status: "open" },
{ title: "Deploy", status: "open" },
];
const { open = [], done = [] } = Object.groupBy(tasks, (t) => t.status);
console.log(open.length, done.length); // 2 1The default values (= []) handle the case where a group is missing, since neither method creates empty groups. A Map cannot be destructured like this. You call get, and you need ?? [] for missing keys:
const tasks = [
{ title: "Write tests", status: "done" },
{ title: "Fix bug", status: "open" },
];
const byStatus = Map.groupBy(tasks, (t) => t.status);
const blocked = byStatus.get("blocked") ?? [];
console.log(blocked.length); // 0
console.log(byStatus.size); // 2The Map has the advantage when the keys are dynamic. size gives the group count directly, while an object needs Object.keys(groups).length. A Map is also directly iterable with for...of, and its has, delete, and set methods make sense if you go on to edit the groups.
Dimension 3: Where the Result Goes Next
Ask where the grouped data ends up. JSON.stringify handles a null-prototype object correctly, but it turns a Map into {}:
const m = Map.groupBy([1, 2, 3, 4], (n) => (n % 2 === 0 ? "even" : "odd"));
console.log(JSON.stringify(m)); // {}
console.log(JSON.stringify(Object.fromEntries(m))); // {"odd":[1,3],"even":[2,4]}If the result goes into an HTTP response, localStorage, a log line, or a template engine that expects plain objects, Object.groupBy saves a conversion step. If you need a Map for the grouping logic and an object for output, Object.fromEntries(map) converts between them. That conversion turns keys into strings, so any distinction the Map kept is lost at that point.
Some libraries test for "plain objects" by checking that the prototype is Object.prototype. A null-prototype result can fail such checks. If you hit this, spread the result into a normal object with { ...groups }. Spreading copies the own properties, and the group arrays are shared, not copied.
Dimension 4: Untrusted Keys
When keys come from user input, such as tags, file names, or query parameters, the null prototype in Object.groupBy protects you. A key like "__proto__" or "toString" becomes an ordinary own property and does not interfere with any inherited member:
const rows = [{ tag: "__proto__" }, { tag: "toString" }, { tag: "news" }];
const groups = Object.groupBy(rows, (r) => r.tag);
console.log(Object.keys(groups)); // ["__proto__", "toString", "news"]
console.log(Object.hasOwn(groups, "__proto__")); // true
console.log(groups.toString.length); // 1That protection lasts only while you keep the null-prototype object. If you copy the groups into an object created with {} using plain assignment (target[key] = value), a "__proto__" key triggers the prototype setter again. Copying with spread or Object.fromEntries creates own properties and avoids that problem. A Map never has this problem, so it is the safer choice when untrusted keys pass through several layers of code.
Dimension 5: Key Order
A Map always iterates in insertion order, which here means the order in which each key first appeared. An object puts integer-like keys such as "2" and "10" first, in ascending numeric order, and then the other string keys in insertion order. If you group by year, status code, or page number and the display order must match the input, use Map.groupBy. If ascending numeric order is what you want anyway, the object's ordering helps you.
Side-by-Side Summary
| Concern | Object.groupBy | Map.groupBy |
|---|---|---|
| Key types kept | Strings and symbols only; others converted | Any value, unchanged |
| Key equality | String equality after conversion | SameValueZero (`NaN` matches `NaN`, objects by reference) |
| Reading a group | `groups.fruit`, destructuring | `groups.get("fruit")` |
| Missing group | `undefined` | `undefined` from `get` |
| Counting groups | `Object.keys(groups).length` | `groups.size` |
| Iteration | `Object.entries(groups)` | `for...of` directly |
| JSON.stringify | Works as expected | Produces `{}` |
| Key order | Integer-like keys first, then insertion | Insertion order |
| Untrusted keys | Safe as long as it stays null-prototype | Always safe |
Common Mistakes When Choosing
- Defaulting to Object.groupBy for object keys. All elements collapse into
"[object Object]", and no error is raised. - Choosing Map.groupBy, then sending it straight to JSON. The response body is
{}. Convert it withObject.fromEntriesfirst. - Looking up Map groups with a fresh object.
map.get({ id: 1 })never matches, because the key was a different object. Keep the original reference, or group by a primitive such as the ID. - Expecting typed keys back from an object. Grouping by a number and then running
Object.keys(groups).map((k) => k * 2)works only through implicit conversion. With aMap, the keys stay numbers. - Picking Map "for performance". Both methods walk the input once. For a one-off grouping, choose based on key type and how the result is used, and benchmark only if profiling points to grouping as the bottleneck.
Exercise
You group log entries by their HTTP status code (numbers like 404, 200, 500) and need to render the groups in the order each code first appeared in the log. Which method should you use, and why?
Show answer
Map.groupBy. With Object.groupBy the numeric codes become integer-like string keys, which objects enumerate in ascending numeric order (200, 404, 500), not first-appearance order. A Map keeps insertion order and also keeps the keys as numbers.
Exercise
An API handler groups products by their category string and returns the result with res.json(groups). A teammate switches to Map.groupBy "for safety". What does the client now receive, and what is the smallest fix?
Show answer
The client receives {}, because JSON.stringify does not serialize Map entries. The smallest fix is to send Object.fromEntries(groups), or to switch back to Object.groupBy, since string category keys gain nothing from a Map.
Exercise
A callback returns user.team, where each team is an object loaded once and shared by reference. Predict what Object.keys(Object.groupBy(users, (u) => u.team)) returns, and write the Map.groupBy line that gets the members of a known team object design.
Show answer
It returns ["[object Object]"], because every team object converts to the same string. With a Map: const members = Map.groupBy(users, (u) => u.team).get(design) ?? []; This works because design is the same reference used as the key.