JavaScript

Preserve ties when sorting records

Return zero from a comparator when two records have equal sort keys. Stable sorting preserves their previous relative order, allowing a deliberate tie rule without inventing a second comparison.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const rows = [{id: "a", score: 2}, {id: "b", score: 1}, {id: "c", score: 2}];
const sorted = rows.toSorted((a, b) => a.score - b.score);
console.log(sorted.map(row => row.id).join(","));

How it works

The lower score moves first, while a and c remain in their original order because their comparator result is zero. This is useful when the source order already represents a meaningful secondary priority, such as arrival order.

Limits and mistakes

Stability does not repair an inconsistent comparator. Always return a negative, zero, or positive result consistently for the same pair. If input order is arbitrary, use an explicit secondary key rather than depending on it as a hidden tie breaker.

Check the result

Expect b,a,c. Swap the two equal-score records in the input and verify that their resulting order follows that change. Add an explicit ID comparison if ties need a universal order.

Sources

Reference documentation for the behavior used in this guide: