JavaScriptFundamental (ES6), part 2
Natural sort so item2 comes before item10 in JavaScript
101 A natural sort, so item2 comes before item10
fairSort a list of names containing numbers the way a person would: item2 before item10. Split each name into runs of digits and runs of everything else, compare run by run, and give the comparator a tie-break so it is total. Then do the same thing in one line with Intl.Collator, and find the number big enough to defeat the hand-written version.
Stuck? Three hints, smallest first
- 1.
text.match(/\d+|\D+/g)splits into alternating number and text runs. - 2. Compare two number runs numerically and two text runs as text. Fall through when they are equal.
- 3.
new Intl.Collator('en', { numeric: true }).compareis the built-in version of the whole thing.
const runs = (text) => text.match(/\d+|\D+/g) ?? [];
function naturalCompare(a, b) {
const left = runs(a);
const right = runs(b);
const shared = Math.min(left.length, right.length);
for (let i = 0; i < shared; i++) {
const x = left[i];
const y = right[i];
if (/^\d/.test(x) && /^\d/.test(y)) {
const difference = Number(x) - Number(y);
if (difference !== 0) return difference;
continue; // equal numbers: 007 and 7 tie here
}
if (x !== y) return x.localeCompare(y, 'en');
}
// Same runs so far: the shorter name first, then the raw text so the order is total.
return left.length - right.length || (a < b ? -1 : a > b ? 1 : 0);
}
const collator = new Intl.Collator('en', { numeric: true });
const files = ['item10', 'item2', 'item1', 'item20', 'item3'];
const plainSort = [...files].sort();
const naturalSort = [...files].sort(naturalCompare);
const collatorSort = [...files].sort(collator.compare);
const invoices = ['Invoice 9.pdf', 'Invoice 10.pdf', 'Invoice 1.pdf', 'Invoice 2.pdf'];
const invoiceOrder = [...invoices].sort(naturalCompare);
const branches = ['ikeja-1', 'apapa-9', 'ikeja-10', 'apapa-10'];
const branchOrder = [...branches].sort(naturalCompare);
const leadingZeros = naturalCompare('item02', 'item2');
const noDigitsAtAll = ['bus stop', 'bus', 'busy'].sort(naturalCompare);
// Past 2^53 the numeric comparison stops being able to tell them apart.
const huge = ['v9007199254740993', 'v9007199254740992'];
const numbersCollapse = Number('9007199254740993') - Number('9007199254740992');
const tieBreakRescuesIt = [...huge].sort(naturalCompare);
console.log('plain sort :', plainSort);
console.log('natural sort :', naturalSort);
console.log('invoices :', invoiceOrder);
console.log('past 2^53 :', numbersCollapse, '<- the difference the comparator sees');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the default sort compares text, so item10 lands before item2', plainSort, ['item1', 'item10', 'item2', 'item20', 'item3']);
test('the natural sort reads the digits as a number', naturalSort, ['item1', 'item2', 'item3', 'item10', 'item20']);
test('and Intl.Collator with numeric: true does the same job in one line', collatorSort, naturalSort);
test('it works with the number in the middle of the name', invoiceOrder, ['Invoice 1.pdf', 'Invoice 2.pdf', 'Invoice 9.pdf', 'Invoice 10.pdf']);
test('text runs still compare as text, so the branch name decides first', branchOrder, ['apapa-9', 'apapa-10', 'ikeja-1', 'ikeja-10']);
test('leading zeros compare equal numerically, so the raw-text tie-break decides', leadingZeros, -1);
test('a list with no digits sorts alphabetically, as it should', noDigitsAtAll, ['bus', 'bus stop', 'busy']);
test('past 2^53 the two numbers subtract to zero, and only the tie-break saves the order', [numbersCollapse, tieBreakRescuesIt], [0, ['v9007199254740992', 'v9007199254740993']]);
Splitting on /\d+|\D+/g is the whole idea: alternating runs, compared pairwise, numbers as numbers and text as text. Everything else is bookkeeping. The tie-break at the end matters more than it looks — a comparator must be consistent, and without it item02 and item2 compare as equal, which makes the result depend on the engine's sort stability rather than on the data.
Then the practical answer: do not write this. Intl.Collator with numeric: true is the same behaviour, implemented against the Unicode collation rules, and the third assertion shows it agreeing. It also handles digits outside ASCII, case and accent sensitivity as options, and locale-specific letter ordering, none of which the hand-rolled version does. Build the collator once and pass collator.compare to sort; constructing it inside the comparator rebuilds it for every comparison.
The last assertion is the honest limit of the manual version. Digits are converted with Number, so two version strings differing past the 53rd bit subtract to exactly 0 and the numeric branch cannot separate them; here the raw-text fallback happens to produce the right answer, which is luck rather than design. For git-style identifiers or long numeric ids, compare the digit runs as strings — by length first, then character by character — or let the collator do it.