Sub topic 13
The Order of Keys in Grouped Results
When you print a grouped result or loop over it, the groups come out in some order. Sometimes that order matches what you expect. Sometimes "2023" jumps ahead of "2025" even though 2025 appeared first in your data. This chapter explains the rules that decide the order, where Object.groupBy and Map.groupBy differ, and how to get the order you want.
This chapter assumes you already know how both methods are called, that Object.groupBy turns keys into strings (or keeps them as symbols), and that Map.groupBy keeps keys unchanged.
Two Separate Orders
A grouped result has two orders, and they follow different rules:
| Order | Object.groupBy | Map.groupBy |
|---|---|---|
| Order of the groups (keys) | Property-key order: array-index keys first, then other strings, then symbols | Insertion order: first time each key is seen |
| Order of elements inside a group | Iteration order of the input | Iteration order of the input |
The elements inside a group are always in the order the input produced them. Both methods walk the iterable once from start to finish and push each element onto the end of its group's array. If "cherries" comes after "bananas" in the input, it also comes after "bananas" in the fruit group.
The order of the keys is where the two methods differ.
Insertion Order: The Common Case
Both methods create each group the first time they see its key. When every key is an ordinary, non-numeric string, an object and a Map give the same result: groups appear in the order their keys first showed up.
const scores = [
{ name: "Ana", grade: "B" },
{ name: "Ben", grade: "A" },
{ name: "Cy", grade: "B" },
{ name: "Di", grade: "C" },
];
const byGrade = Object.groupBy(scores, ({ grade }) => grade);
console.log(Object.keys(byGrade)); // ["B", "A", "C"]
console.log(byGrade.B.map((s) => s.name)); // ["Ana", "Cy"]
const byGradeMap = Map.groupBy(scores, ({ grade }) => grade);
console.log([...byGradeMap.keys()]); // ["B", "A", "C"]"B" comes first because Ana is the first element. When Cy adds a second "B" later, the "B" group doesn't move. Adding to a group that already exists never changes where that group sits.
How Object Property Order Works
Plain objects don't simply remember insertion order. The language spec sorts an ordinary object's own keys into three buckets, and Object.keys, Object.entries, for...in, JSON.stringify, and Reflect.ownKeys all follow these buckets:
- Array-index keys, in ascending numeric order. An array-index key is a string that is the canonical form of a whole number from 0 to 4294967294, such as
"0","7", or"2025". - All other string keys, in the order they were created.
- Symbol keys, in the order they were created.
Object.keysandObject.entriesskip symbols, butReflect.ownKeysincludes them.
Your callback might return numbers, such as years, IDs, or bucket sizes. Object.groupBy turns them into strings like "2025", and those strings fall into the first bucket. So the object reorders them, and the Map does not.
const orders = [
{ id: 1, year: 2025 },
{ id: 2, year: 2023 },
{ id: 3, year: 2024 },
{ id: 4, year: 2023 },
];
const byYear = Object.groupBy(orders, ({ year }) => year);
console.log(Object.keys(byYear)); // ["2023", "2024", "2025"]
const byYearMap = Map.groupBy(orders, ({ year }) => year);
console.log([...byYearMap.keys()]); // [2025, 2023, 2024]Neither result is wrong. The object sorted the years for you, which is often handy. The Map kept the order the data arrived in, which you need when that order means something, such as "most recent activity first."
Edge Cases in the First Bucket
Only canonical integer strings in range go into the first bucket. Strings that look numeric but aren't canonical stay in creation order with the other strings. This catches people who group by codes, zero-padded IDs, or decimal values.
const sym = Symbol("other");
const items = ["x", "10", "y", "2", "01", "-1", "1.5", "z"];
const groups = Object.groupBy(items, (s) => (s === "z" ? sym : s));
console.log(Reflect.ownKeys(groups));
// ["2", "10", "x", "y", "01", "-1", "1.5", Symbol(other)]
console.log(Object.keys(groups));
// ["2", "10", "x", "y", "01", "-1", "1.5"]Here is why each key landed where it did:
| Key | Bucket | Reason |
|---|---|---|
| `"2"`, `"10"` | 1 | Canonical whole numbers in range, so they are sorted numerically |
| `"01"` | 2 | Leading zero, so it is not the canonical form of 1 |
| `"-1"` | 2 | Negative numbers are not array indexes |
| `"1.5"` | 2 | Not a whole number |
| `"4294967295"` | 2 | One past the largest array index |
| `Symbol(other)` | 3 | Symbols always come last |
Order Can Change When You Convert
Moving a result between a Map and an object can quietly reorder it. Object.fromEntries builds an ordinary object, so integer-like keys get sorted again. JSON.stringify follows object order too, so a Map you convert for an API response won't keep its insertion order.
const visits = [
{ page: "home", day: 15 },
{ page: "about", day: 3 },
{ page: "home", day: 9 },
];
const byDay = Map.groupBy(visits, ({ day }) => day);
console.log([...byDay.keys()]); // [15, 3, 9]
const asObject = Object.fromEntries(byDay);
console.log(Object.keys(asObject)); // ["3", "9", "15"]
console.log(JSON.stringify(Object.keys(asObject))); // ["3","9","15"]If the order has to survive serialization, send an array of entries, such as [...byDay] or [...byDay].map(([day, items]) => ({ day, items })). Arrays keep their order everywhere.
Getting the Order You Want
Choose a strategy based on where the order you need comes from.
Order from the data
When the order of first appearance matters, use Map.groupBy. It keeps insertion order for every key type.
A fixed, known order
When the categories have a meaning-based order, such as priorities, weekdays, or sizes, don't rely on key order at all. Iterate over your own list of keys. This also lets you show empty groups.
const tickets = [
{ id: 1, priority: "low" },
{ id: 2, priority: "high" },
{ id: 3, priority: "medium" },
{ id: 4, priority: "high" },
];
const byPriority = Object.groupBy(tickets, ({ priority }) => priority);
const levels = ["high", "medium", "low", "none"];
for (const level of levels) {
const group = byPriority[level] ?? [];
console.log(level, group.map((t) => t.id));
}
// high [2, 4]
// medium [3]
// low [1]
// none []A computed order
Sort the entries explicitly. For a Map, build a new Map from sorted entries, because a Map remembers whatever order you insert into it.
const orders = [
{ id: 1, year: 2025 },
{ id: 2, year: 2023 },
{ id: 3, year: 2024 },
];
const byYear = Map.groupBy(orders, ({ year }) => year);
const newestFirst = new Map([...byYear].sort(([a], [b]) => b - a));
console.log([...newestFirst.keys()]); // [2025, 2024, 2023]
const bySize = Object.groupBy(["kiwi", "fig", "plum", "pear", "apple"], (w) =>
w.length > 3 ? "long" : "short"
);
const largestFirst = Object.entries(bySize).sort(
([, a], [, b]) => b.length - a.length
);
console.log(largestFirst.map(([key]) => key)); // ["long", "short"]You can't sort an object's integer-like keys into descending order. The object will always put them back in ascending order. Keep the sorted result as an array of entries or as a Map.
Ordering elements inside groups
Element order follows input order, so sort the input before grouping. Every group then comes out sorted. Use toSorted so you don't change the original array.
const people = [
{ name: "Cy", team: "red" },
{ name: "Ana", team: "blue" },
{ name: "Ben", team: "red" },
];
const byTeam = Object.groupBy(
people.toSorted((a, b) => a.name.localeCompare(b.name)),
({ team }) => team
);
console.log(byTeam.red.map((p) => p.name)); // ["Ben", "Cy"]Sorting the input also changes which key each group sees first. That affects Map.groupBy order and the second bucket of an object's keys.
Common Mistakes
- Expecting numeric keys to stay in input order in an object. They get sorted ascending. Use a Map if input order matters.
- Expecting numeric-looking keys to be sorted.
"01","-5", and"2.5"are not array indexes, so they keep creation order. - Writing tests that depend on
Object.keysorder. A test like that can pass or fail depending on the data. Compare against an explicit key list, or sort the keys before comparing. - Converting a Map with
Object.fromEntriesorJSON.stringify. Integer-like keys get re-sorted. Serialize an array of entries instead.
Exercise
What does this log? const r = Object.groupBy([30, 5, 12, 5, 30, 7], (n) => (n >= 10 ? n : "small")); console.log(Object.keys(r));
Show answer
["12", "30", "small"]. The numbers 30 and 12 become the array-index keys "30" and "12", which go first in ascending numeric order. "small" is an ordinary string key, so it comes after them, even though it was created after "30" but before "12". Within the groups, r.small is [5, 5, 7] and r["30"] is [30, 30], in input order.
Exercise
You group log entries by HTTP status code with Map.groupBy, then return Object.fromEntries(result) from an API. The client complains that the groups no longer match the order in which each status code first appeared. Why, and what should you return instead?
Show answer
Object.fromEntries builds a plain object. Status codes such as 404 and 200 become array-index keys, which the object sorts in ascending numeric order, and JSON.stringify keeps that sorted order. Return an array of entries such as [...result] or [...result].map(([status, entries]) => ({ status, entries })). Arrays keep their order through serialization.
Exercise
Which of these keys, returned by an Object.groupBy callback, end up in the sorted first bucket: 42, "042", -3, 7.0, "7.0", true?
Show answer
Only 42 and 7.0. The number 42 becomes "42". The number 7.0 becomes "7", because String(7.0) is "7". Both are canonical integer strings. "042" has a leading zero, -3 becomes "-3", which is negative, "7.0" is not canonical, and true becomes "true". All four of those keep creation order in the second bucket.