Sub topic 13
The Order of Keys in Grouped Results
This chapter assumes you know how Object.groupBy and Map.groupBy build their results, and that you have seen how Object.groupBy converts keys to strings. You should also be comfortable with Object.keys and with spreading a Map's keys into an array.
When you loop over a grouped result, the order of the groups can surprise you. Both methods add a group the first time they see its key. A Map keeps that order. A plain object applies its own ordering rules on top of it.
How Each Method Orders Groups
Map.groupBy returns a Map, and a Map always iterates keys in insertion order. The first key the callback returns comes first, the second new key comes second, and so on.
Object.groupBy returns an object, so its keys follow the standard property order that Object.keys, Object.entries, and for...in use:
- Integer-like keys (canonical array indexes such as
"0","2","10") come first, in ascending numeric order. - Other string keys follow, in insertion order.
- Symbol keys come last, in insertion order.
Object.keysskips them, butReflect.ownKeysincludes them.
Seeing the Difference
Here the key "10" is inserted before "2", but the object lists them numerically:
const keyFor = (s) => (s === "b" ? "10" : "2");
const obj = Object.groupBy(["b", "a"], keyFor);
console.log(Object.keys(obj)); // ["2", "10"]
const map = Map.groupBy(["b", "a"], keyFor);
console.log([...map.keys()]); // ["10", "2"]Mixed keys show both rules at once. Integer-like keys jump to the front, and the remaining strings keep the order they first appeared in:
const labels = { x: "b", y: "2", z: "a", w: "1" };
const obj = Object.groupBy(["x", "y", "z", "w"], (c) => labels[c]);
console.log(Object.keys(obj)); // ["1", "2", "b", "a"]
const map = Map.groupBy(["x", "y", "z", "w"], (c) => labels[c]);
console.log([...map.keys()]); // ["b", "2", "a", "1"]Order Inside Each Group
The elements inside each group array always keep the order of the input. If "bananas" comes before "cherries" in the source, it comes first in the fruit group too, with either method. Only the order of the groups themselves differs between the two methods.
Getting the Order You Want
If the order of groups matters, pick one of these approaches:
| Goal | Approach |
|---|---|
| Order of first appearance | Use `Map.groupBy` |
| Sorted order | Sort the entries explicitly, for example `Object.entries(obj).sort(...)` |
| Object result with numeric-looking labels kept in insertion order | Prefix keys, such as `"score-10"` |
Sorting explicitly is the clearest option because it does not depend on engine ordering rules that readers may not know:
const scores = [95, 72, 100, 78, 91];
const byBand = Object.groupBy(scores, (s) => String(Math.floor(s / 10) * 10));
const descending = Object.entries(byBand).sort(([a], [b]) => Number(b) - Number(a));
console.log(descending.map(([band]) => band)); // ["100", "90", "70"]Exercise
What does Object.keys(Object.groupBy([3, 1, 2], (n) => (n === 3 ? "z" : String(n * 5)))) log, and what would [...Map.groupBy(...).keys()] log with the same arguments?
Show answer
The callback returns "z", "5", then "10". Object.groupBy puts the integer-like keys first in ascending order, then the other strings: ["5", "10", "z"]. Map.groupBy keeps insertion order: ["z", "5", "10"].
Exercise
You group log entries by HTTP status code with Object.groupBy and want to show groups in the order each status first appeared. Why does this fail, and what is the fix?
Show answer
Status codes such as "500" and "200" are integer-like keys, so the object lists them in ascending numeric order no matter when they first appeared. Use Map.groupBy, which keeps insertion order, or prefix the keys so they are no longer integer-like.