Array Sort Multi Key Stability
Sort records by multiple keys with a composed comparator and rely on ES2019 sort stability so equal keys keep their input order.
Code
const ledger = [
{ region: 'eu', amount: 80, id: 'e1' },
{ region: 'na', amount: 95, id: 'n1' },
{ region: 'eu', amount: 120, id: 'e2' },
{ region: 'na', amount: 95, id: 'n2' },
];
// 组合比较器:区域升序 → 金额降序;相等时保持输入顺序(ES2019 稳定排序)
const sorted = [...ledger].sort((a, b) =>
a.region.localeCompare(b.region) || b.amount - a.amount,
);
for (const row of sorted) {
console.log(`${row.region} ${row.amount} ${row.id}`);
}
// 用原始序号验证稳定性:同键两条记录 n1 应排在 n2 前
const indices = sorted.map((row) => ledger.indexOf(row));
console.log('stable order:', indices.every((v, i, arr) => i === 0 || arr[i - 1] < v));Output
Captured from a sandboxed run of this snippet in the build pipeline.
eu 120 e2
eu 80 e1
na 95 n1
na 95 n2
stable order: falseHow the snippet works
Iteration happens inside for (const row of sorted) — everything outside it runs once.
The entire file operates over top-level bindings: ledger, sorted, indices.
Applying it
Running the file prints labeled results such as stable order: — each operation’s effect is visible in the output.
Statements that matter
const sorted = [...ledger].sort((a, b) =>
a.region.localeCompare(b.region) || b.amount - a.amount,
);
const indices = sorted.map((row) => ledger.indexOf(row));
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `ledger`, `sorted`, `indices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.