❯ehsan.blog
~/blog/your-object-reorders-itself-when-the-ids-are-numbers — zsh
❯cat your-object-reorders-itself-when-the-ids-are-numbers.md

Your object reorders itself when the IDs are numbers

·10 min read

Your object reorders itself when the IDs are numbers — article card for a post by Ehsan Shahid

A leaderboard came back wrong. The API sent three players in rank order — Ana first, then Bilal, then Cara — and the page drew them as Bilal, Cara, Ana. No sorting code anywhere. No sort at all, in fact. That was the part that made no sense for about an hour.

The code was this boring:

js
const players = await res.json()
// [ { id: 103, name: "Ana" }, { id: 7, name: "Bilal" }, { id: 42, name: "Cara" } ]

const byId = Object.fromEntries(players.map((p) => [p.id, p]))

for (const p of Object.values(byId)) {
  console.log(p.name)
}

Run it. You get Bilal, then Cara, then Ana. 7, 42, 103.

Nothing sorted that list. JavaScript did, and it did it the moment those IDs became keys.

The rule nobody tells you on day one

An object does not keep your keys in one line. It keeps them in two groups, and it always hands them back in this order:

  1. Keys that look like an array index, sorted smallest to largest, as numbers.
  2. Every other string key, in the order you added them.

"7", "42" and "103" all look like array indexes. So they get counted, lined up low to high, and served first. Insertion order never gets a say.

Watch it happen with a mixed object:

js
const o = {}
o.b = 1
o["10"] = 1
o.a = 1
o["9"] = 1

Object.keys(o) // [ "9", "10", "b", "a" ]

"9" and "10" jump to the front in numeric order. b and a stay in the order they were written, behind them. Notice "9" beats "10", which is the opposite of what you would get sorting them as text.

This is not a Node thing or a V8 thing. It is written into the language itself, in the OrdinaryOwnPropertyKeys step of the spec, so every engine does it the same way. I ran the same four lines in Bun to be sure, and it prints 9,10,b,a too.

There is a reason the rule exists. An array in JavaScript is an object whose keys happen to be "0", "1", "2", and so on, and engines store those index-shaped keys in a separate, tightly packed slot list so that arr[500] is a fast jump rather than a hash lookup. A plain object gets the same treatment for any key that fits the same shape. The front-of-the-queue ordering is that storage split leaking out into Object.keys. It is not a bug, and it is not going to be fixed, because arrays depend on it.

How bad it gets with real data

Three players is a cute example. I wanted a number, so I built a thousand rows with IDs between 1 and 9999 in a shuffled rank order, pushed them through Object.fromEntries, and counted how many came out in a different position than they went in. Then I ran it five times.

text
out-of-place rows per run (%): 99.9, 99.9, 99.9, 99.9, 100.0
sorted ascending by id: true
map keeps order: true

At worst 99.9% of the rows moved. Not “a few near the top” — effectively the entire list, rebuilt into numeric ID order. The one or two rows that stayed put were coincidences, rows whose rank happened to match their sorted position.

That is the thing to hold on to. This is not a small perturbation you might miss in a code review of the output. It replaces your ordering with a completely different one, and the replacement looks perfectly tidy, which is exactly why nobody suspects it.

”Looks like an array index” is pickier than you think

A key only gets the front-of-the-line treatment if it is the canonical text of a number between 0 and 4294967294. Write that number any other way and it stays an ordinary string:

js
const b = {}
b["01"] = 1
b["1"] = 1
b["+1"] = 1
b["1.0"] = 1
b[" 1"] = 1
b["-1"] = 1

Object.keys(b) // [ "1", "01", "+1", "1.0", " 1", "-1" ]

Only "1" moved. "01" has a leading zero, "+1" has a sign, "1.0" has a decimal point, " 1" has a space, and "-1" is negative. Not one of them is the plain, shortest spelling of an array index, so all five keep their place in line.

The top of the range is just as sharp:

js
const c = {}
c["zzz"] = 1
c["4294967294"] = 1
c["4294967295"] = 1
c["4294967296"] = 1

Object.keys(c) // [ "4294967294", "zzz", "4294967295", "4294967296" ]

4294967294 is the largest index an array can hold, so it is treated as a number and jumps the queue. 4294967295 is one too far. It sits in the second group, after a key spelled zzz, in the order it was added. Two numbers one apart, two different rules.

It is not just Object.keys

This caught me out because I assumed only Object.keys cared. Everything that walks an object’s keys walks them in the same order:

js
const d = { b: 1, "10": 1, a: 1, "9": 1 }

JSON.stringify(d)      // '{"9":1,"10":1,"b":1,"a":1}'
Object.entries(d)      // [ ["9",1], ["10",1], ["b",1], ["a",1] ]
Object.values(d)       // [ 1, 1, 1, 1 ]  (same order)
Object.keys({ ...d })  // [ "9", "10", "b", "a" ]

A for...in loop does it. Object.getOwnPropertyNames does it. structuredClone does it. And JSON.parse does it on the way in, so text that arrived in one order becomes an object in another:

js
Object.keys(JSON.parse('{"b":1,"10":2,"a":3,"9":4}'))
// [ "9", "10", "b", "a" ]

That last one matters more than it looks. If a service hands you a JSON object keyed by numeric IDs and you trust the order it was printed in, you have already lost it. The order was gone before your code read the first key.

Deleting a key and adding it back does not buy you a place at the end, either:

js
const big = { b: 1, "10": 1 }
delete big["10"]
big["10"] = 1

Object.keys(big) // [ "10", "b" ]

It is an index. It goes first. Always.

Why your tests never caught it

Here is the cruel part, and the reason this one hides for so long.

Test fixtures usually use friendly fake IDs: "user-a", "abc123", a UUID from a seed file. None of those look like array indexes, so every one of them keeps insertion order, and your assertion passes:

js
const seed = [ { id: "a3", name: "Ana" }, { id: "b7", name: "Bilal" } ]

Object.values(Object.fromEntries(seed.map((u) => [u.id, u])))
// Ana, then Bilal. Correct. Green tick. Ship it.

Then production hands you auto-increment IDs from Postgres, and the same function quietly starts sorting. The code did not change. The data changed shape, and the shape of the data was secretly part of the logic.

It does not even need the IDs to be numbers. Strings work just as well, because a key is always text in the end:

js
const users = [ { id: "103" }, { id: "7" } ]
Object.keys(Object.fromEntries(users.map((u) => [u.id, u]))) // [ "7", "103" ]

And if you are wondering whether a number key stays a number: it does not. Object.keys({ 10: 1 })[0] is the string "10". Objects only have string keys (and symbols, which Object.keys ignores entirely).

Four places this lands

Once you know the shape of it, you start seeing where it hides:

  • A ranked list rendered from a lookup object. The leaderboard above. Rank order in, ID order out.
  • A CSV or spreadsheet export. If the column order comes from Object.keys of a row and any column is named 2024 or 12, those columns march to the front of the file.
  • A log line. A structured log entry built from an object with numeric keys prints its fields in a different order than you wrote them, which makes two otherwise identical lines look different when you diff them.
  • A snapshot test. JSON.stringify of an object with numeric keys is stable, so the test passes — it just locked in the wrong order and now defends it.

The CSV one is the meanest of the four, because a spreadsheet that opens with the year columns first reads as a formatting mistake, and you will go looking in the export code for a sort that was never written.

The fix: stop asking an object to remember order

Once you see the rule, the fix writes itself. An object is a bag you reach into by name. It was never a list. If order is part of your data, keep it in something that is built to hold order.

Keep the array. The cheapest fix, most of the time. You already had the order; the lookup object threw it away. Keep both, and let each one do its job:

js
const order = players                                  // for rendering
const byId = new Map(players.map((p) => [p.id, p]))    // for lookups

order.map((p) => p.name)   // Ana, Bilal, Cara
byId.get(7).name           // "Bilal"

Use a Map. A Map keeps keys exactly as you put them in, whatever they look like, and it keeps the key’s real type instead of turning it into text:

js
const byId = new Map(players.map((p) => [p.id, p]))

;[...byId.values()].map((p) => p.name) // Ana, Bilal, Cara
byId.get(7)                            // the number 7, not "7"

One trap to know about here: the moment you turn that Map back into a plain object, the sorting comes straight back.

js
JSON.stringify(Object.fromEntries(byId))
// '{"7":{...},"42":{...},"103":{...}}'  — shuffled again

So if the order has to survive a trip over the wire, send an array of objects, not an object keyed by ID. An array is the only JSON shape that promises order.

Or prefix the keys, if you are stuck with a plain object for some reason:

js
Object.keys(Object.fromEntries(players.map((p) => ["u_" + p.id, p])))
// [ "u_103", "u_7", "u_42" ]  — insertion order kept

"u_103" is not an array index, so it never jumps. This works, and I would still reach for a Map first. A prefix is a rule a future reader has to know about; a Map says what it means on its own.

A check you can paste

If you want to see all of it at once, save this as order.mjs and run node order.mjs. It passes on Node 22 and prints nothing if everything holds:

js
import assert from "node:assert/strict"

const players = [
  { id: 103, name: "Ana" },
  { id: 7, name: "Bilal" },
  { id: 42, name: "Cara" },
]

// The bug: the object sorts the numeric keys for you.
const asObject = Object.fromEntries(players.map((p) => [p.id, p]))
assert.deepEqual(
  Object.values(asObject).map((p) => p.name),
  ["Bilal", "Cara", "Ana"],
)

// The fix: a Map keeps what you gave it.
const asMap = new Map(players.map((p) => [p.id, p]))
assert.deepEqual(
  [...asMap.values()].map((p) => p.name),
  ["Ana", "Bilal", "Cara"],
)
assert.equal(asMap.get(7).name, "Bilal")

// Non-index keys are safe in an object, which is why tests pass.
assert.deepEqual(Object.keys({ b: 1, a: 1, "x9": 1 }), ["b", "a", "x9"])

Change those IDs to UUIDs and the first assertion fails — which is a neat way to prove to yourself that your fixtures, not your code, were holding the bug shut.

The part worth remembering

JavaScript will happily take order away from you without a warning, an error, or a line in the stack trace. A missing value becomes the literal word “undefined” in your query string. A Headers object spreads into nothing at all. One BigInt deletes every other field in your log line. This one is the same family: the language did exactly what it promised, and what it promised was never what you assumed.

If the order of something matters, say so in the type you pick. Arrays and Maps keep order because keeping order is their job. Objects do not, and the day your IDs turn into numbers is the day they stop pretending.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.