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:
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:
| Comparison | Rule |
|---|---|
| Different scores | Higher score appears first |
| Equal scores, different IDs | Smaller string ID appears first |
| Same score and same ID | Comparator 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:
| |
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:
| |
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:
| |
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.