Default Sort Compares Strings Not Numbers
Without a comparator, sort stringifies elements and orders them by code units, so 10 lands before 2; numeric arrays need a subtraction comparator.
Code
// 默认 sort 把元素转成字符串再按码元比较
const versions = [10, 9, 100, 2];
console.log('default sort:', versions.slice().sort()); // [10, 100, 2, 9]
// 比较函数返回数值:负数 a 在前,正数 b 在前,0 保持原相对顺序
console.log('numeric sort:', [10, 9, 100, 2].sort((a, b) => a - b));
// undefined 由排序实现固定放到末尾,比较函数不会收到它
console.log('with undefined:', [3, undefined, 1].sort((a, b) => a - b));
// 相等元素保持原有相对顺序(规范保证 sort 是稳定排序)
console.log('stable ties:', [['x', 2], ['y', 2], ['z', 1]].sort((a, b) => a[1] - b[1]).map((p) => p[0]));
// 字符串的人类语序排序也要显式选择:默认字典序不等于 locale 顺序
const names = ['Zoë', 'Adam', 'aña'];
console.log('code-unit order:', names.slice().sort());
console.log('locale order:', names.slice().sort(new Intl.Collator('es').compare));Output
Captured from a sandboxed run of this snippet in the build pipeline.
default sort: [ 10, 100, 2, 9 ]
numeric sort: [ 2, 9, 10, 100 ]
with undefined: [ 1, 3, undefined ]
stable ties: [ 'z', 'x', 'y' ]
code-unit order: [ 'Adam', 'Zoë', 'aña' ]
locale order: [ 'Adam', 'aña', 'Zoë' ]The stringification trap
Without a comparator, sort converts elements to strings and orders by code units: [10, 9, 100, 2] sorts to [10, 100, 2, 9], printed as default sort. A subtraction comparator (a, b) => a - b fixes numeric order.
Spec corners
undefined values are placed at the end by the sort implementation and never reach the comparator — visible in the with undefined line. Ties keep their original relative order because sort is stable, shown by the stable ties output preserving x before y.
Human ordering is separate
Even strings need a deliberate choice: default order is by code units, so Zoë, Adam, aña sorts with the accented names by raw code units, while Intl.Collator(‘es’).compare applies Spanish collation rules for the locale order line.
Interactive Tools for This Topic
FAQ
- Why does 10 sort before 2 without a comparator?
- Default sort stringifies elements and compares code units, so "10" < "2" lexicographically; numeric order needs the a - b comparator.
- What does sort stability guarantee?
- Elements that compare equal keep their original relative order, which the stable ties line demonstrates with x and y both mapped to 2.
Report a problem with this exampleOpens a pre-filled issue on GitHub.