Files and data

Sort exported records with a deterministic tie key

When generating a comparison-friendly report, sort by an explicit primary field and a stable secondary identifier. A tie key makes the output less dependent on incidental input order.

Worked example

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

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

How it works

The numeric comparison groups smaller counts first. When counts match, ordinary string ordering of the chosen ASCII-style IDs breaks the tie. The original array remains unchanged, which makes it safe to retain an unsorted source view.

Limits and mistakes

Validate count as a finite number and ID as a string before sorting. This machine ordering is different from locale-aware name sorting. More complex canonical exports need rules for all fields, not just a stable row order.

Check the result

Expect c,a,b. Shuffle the same records and confirm the sorted ID sequence stays the same. Add a duplicate ID if the source does not guarantee uniqueness.

Sources

Reference documentation for the behavior used in this guide: