Sort JavaScript Leaderboards with Explicit ID Tie-Breakers

A leaderboard refresh returns the same players and scores in a different arrival order. Sorting only by score leaves tied players in that new order, so their rows move even though no score changed.

Define a second comparison key when the interface needs repeatable ordering. This example sorts by descending score, then ascending unique player ID. It uses ordinary data records, nonnegative safe integer scores, and exact nonempty string IDs. The code runs in modern browsers or Node.js 20 or later without a dependency.

See What Stable Sorting Actually Preserves

Stable sorting preserves the input order of records that compare equal:

1
2
3
4
5
6
const a = { id: "a", score: 100 };
const b = { id: "b", score: 100 };
const byScore = (left, right) => right.score - left.score;

console.log([b, a].sort(byScore).map(row => row.id).join(",")); // b,a
console.log([a, b].sort(byScore).map(row => row.id).join(",")); // a,b

Both outputs satisfy the score comparison. Stability does not make equal-score records arrive in a canonical order. The ECMAScript sorting specification requires stable ordering for equal comparisons; it does not supply an application-specific secondary key.

If preserving arrival order is your desired policy, the score comparator is sufficient. If a refresh must produce the same player order for the same data, compare a unique ID when scores tie.

Define the Complete Ordering Contract

Use this comparison sequence:

ComparisonRule
Different scoresHigher score appears first
Equal scores, different IDsSmaller string ID appears first
Same score and same IDComparator returns zero

IDs use JavaScript string ordering by UTF-16 code units. For example, "10" precedes "2"; these are identifiers, not numeric quantities. This order is case-sensitive and does not trim or normalize strings. It is useful for a repeatable machine key, rather than alphabetical ordering of display names.

Require each ID to occur once in a snapshot. Two conflicting records with the same ID need an upstream selection rule; a sort comparator should not silently choose one or merge their fields. Unique IDs make the secondary key distinguish every pair of different players.

Scores must be numbers from zero through Number.MAX_SAFE_INTEGER. Reject numeric strings, fractions, NaN, and infinities before sorting. This keeps the numeric comparison meaningful and avoids precision loss already present in unsafe integer inputs. Negative zero is accepted and compares equal to zero.

Validate Before Sorting a Copy

Save this module as leaderboard.mjs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export function compareEntries(left, right) {
  const scoreOrder = right.score - left.score;
  if (scoreOrder !== 0) return scoreOrder;
  if (left.id < right.id) return -1;
  if (left.id > right.id) return 1;
  return 0;
}

export function sortLeaderboard(records) {
  if (!Array.isArray(records)) {
    throw new TypeError("records must be an array");
  }

  const ids = new Set();
  const copy = [];
  for (const row of records) {
    if (row === null || typeof row !== "object" || Array.isArray(row) ||
        !Object.hasOwn(row, "id") || !Object.hasOwn(row, "score")) {
      throw new TypeError("each record must own id and score fields");
    }
    if (typeof row.id !== "string" || row.id.length === 0) {
      throw new TypeError("id must be a nonempty string");
    }
    if (!Number.isSafeInteger(row.score) || row.score < 0) {
      throw new TypeError("score must be a nonnegative safe integer");
    }
    if (ids.has(row.id)) {
      throw new TypeError("duplicate player id");
    }
    ids.add(row.id);
    copy.push(row);
  }
  return copy.sort(compareEntries);
}

compareEntries expects already validated records. It returns a negative number, zero, or a positive number, rather than a Boolean. Returning only true or false fails to express both directions of an ordering. The comparator reads the same fields consistently and has no side effects.

Validation happens outside the comparator because an engine need not compare every element. A single-element array still needs its record checked. Iterating the input also exposes ordinary sparse-array holes as undefined, which this helper rejects.

sort() changes its receiver , so the helper sorts a newly allocated array. It keeps the original record references. This contract assumes ordinary data properties, without accessors, proxies, or concurrent mutation of the records during the call.

Use the Same Keys on Every Refresh

Run this beside the module:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { sortLeaderboard } from "./leaderboard.mjs";

const records = [
  { id: "p20", score: 900 },
  { id: "p03", score: 1200 },
  { id: "p01", score: 900 },
];
const sorted = sortLeaderboard(records);
console.log(sorted.map(row => `${row.id}:${row.score}`).join(","));
console.log(records.map(row => row.id).join(","));
// p03:1200,p01:900,p20:900
// p20,p03,p01

The second line shows that the input array retains its order. Another permutation of these same records produces the same sorted ID sequence. Scores remain the primary key; IDs only decide score ties.

For localized display names, define a separate collation policy and retain a unique final key if multiple names compare equal. This recipe deliberately uses exact string IDs so that ordering does not depend on a user’s locale. Use the same score direction and ID comparison on the server if both layers present one shared ranking.

Test Permutations and Comparator Consistency

Save this as test-leaderboard.mjs and run node test-leaderboard.mjs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import assert from "node:assert/strict";
import { compareEntries, sortLeaderboard } from "./leaderboard.mjs";

const a = Object.freeze({ id: "a", score: 10 });
const b = Object.freeze({ id: "b", score: 10 });
const c = Object.freeze({ id: "c", score: 20 });
const input = Object.freeze([b, c, a]);
const expected = [c, a, b];
for (const rows of [[a, b, c], [a, c, b], [b, a, c],
                    [b, c, a], [c, a, b], [c, b, a]]) {
  assert.deepEqual(sortLeaderboard(rows), expected);
}
assert.deepEqual(sortLeaderboard(input), expected);
assert.deepEqual(input, [b, c, a]);
assert.equal(sortLeaderboard(input)[0], c);
assert.notEqual(sortLeaderboard(input), input);
assert.deepEqual(sortLeaderboard([]), []);

for (const left of input) {
  assert.equal(compareEntries(left, left), 0);
  for (const right of input) {
    const forward = Math.sign(compareEntries(left, right));
    const backward = Math.sign(compareEntries(right, left));
    assert.ok(forward === -backward);
    for (const last of input) {
      if (compareEntries(left, right) <= 0 &&
          compareEntries(right, last) <= 0) {
        assert.ok(compareEntries(left, last) <= 0);
      }
    }
  }
}

for (const score of [NaN, Infinity, -1, 1.5, "10",
                     Number.MAX_SAFE_INTEGER + 1]) {
  assert.throws(() => sortLeaderboard([{ id: "a", score }]), TypeError);
}
assert.throws(() => sortLeaderboard([a, { id: "a", score: 11 }]), TypeError);
assert.throws(() => sortLeaderboard([{ id: "", score: 0 }]), TypeError);
assert.throws(() => sortLeaderboard(new Array(1)), TypeError);
assert.throws(() => sortLeaderboard(null), TypeError);

console.log("Leaderboard checks passed.");

The permutation checks distinguish a complete comparison from score-only stable sorting. The pair and triple checks exercise reflexivity, opposite comparison directions, and transitivity on the fixtures. Frozen inputs and reference checks verify that only the result array is reordered.

This is a snapshot ordering rule. It does not prevent players from moving when scores actually change, assign competition ranks to ties, or keep separate paginated requests consistent while the server updates. Those behaviors need their own rules. For a fixed set of validated players and scores, the unique ID tie-breaker makes the displayed order repeatable.