Sort file names naturally in JavaScript
Intermediate · 3 min read
Sort file1.txt, file9.txt and file10.txt with a plain sort() and file10.txt lands in the middle, before file9.txt. People expect 1, 9, 10, the way a file manager shows them. That human-friendly order is called natural sorting, and JavaScript can do it with one option.
In this tutorial you will see why the plain sort gets it wrong, fix it with localeCompare and Intl.Collator, and learn the old trick of zero-padding that makes even a plain sort correct. You should know how to call sort on an array and pass it a compare function.
Why plain sort() gets it wrong
With no compare function, sort() compares items as text, one character at a time. file10.txt and file9.txt match for four characters, file. Then it compares 1 against 9. 1 comes first, so file10.txt goes first. It never notices that 10 is a bigger number than 9.
This is called lexical order: dictionary order, character by character.
Reading digits as numbers
localeCompare compares two strings using language rules. Its numeric: true option changes one thing: a run of digits is read as a whole number. So it compares 10 against 9 as numbers, and 9 wins.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
52 Sorting file names naturally
fairSort ['file10.txt', 'file9.txt', 'file1.txt'] so that 9 comes before 10. Then show the trick that makes the plain sort correct without a collator.
Stuck? Three hints, smallest first
- 1. The default sort is lexical, so
file10precedesfile9. - 2.
localeComparewith{ numeric: true }reads digit runs as numbers. - 3. Zero-padding the numbers makes the lexical order match the numeric one.
Step 1: see the problem
const files = ['file10.txt', 'file9.txt', 'file1.txt'];
const lexical = [...files].sort();
console.log(lexical); // [ 'file1.txt', 'file10.txt', 'file9.txt' ]
[...files] makes a copy, because sort rearranges the array it is called on. The copy is sorted lexically, so file10.txt comes before file9.txt.
Step 2: sort naturally with localeCompare
const files = ['file10.txt', 'file9.txt', 'file1.txt'];
const natural = [...files].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
console.log(natural); // [ 'file1.txt', 'file9.txt', 'file10.txt' ]
console.log(files); // [ 'file10.txt', 'file9.txt', 'file1.txt' ]
The compare function returns a negative number when a should come first and a positive one when b should, which is exactly what sort expects. The original list is unchanged, because we sorted a copy.
Step 3: a collator for reuse
localeCompare may set up its language rules again on every call. An Intl.Collator sets them up once and gives you a ready-made compare function:
const naturally = new Intl.Collator('en', { numeric: true }).compare;
console.log(['b10', 'b9'].sort(naturally)); // [ 'b9', 'b10' ]
console.log(['b', 'a'].sort(naturally)); // [ 'a', 'b' ]
naturally can be passed straight to sort. Letters are still sorted as letters; only the digit runs are treated as numbers.
Step 4: the same trap with real numbers
console.log([10, 9, 1].sort()); // [ 1, 10, 9 ]
console.log([10, 9, 1].sort((a, b) => a - b)); // [ 1, 9, 10 ]
This surprises almost everyone. Even an array of actual numbers is sorted as text when you give sort no compare function, because it turns every item into a string first. For numbers, pass (a, b) => a - b: a negative result puts a first.
Step 5: zero-padding
If you choose the file names yourself, there is a trick that needs no special sorting at all:
console.log(['file10', 'file09'].sort()); // [ 'file09', 'file10' ]
console.log(['002', '001', '010'].sort()); // [ '001', '002', '010' ]
Padding every number to the same width with leading zeros makes the lexical order match the numeric order. 0 comes before 1, so file09 sorts before file10. Every tool that sorts text gets it right, which is why exported photos and log files are often named 001, 002 and so on.
Step 6: ignoring case
const caseless = new Intl.Collator('en', { sensitivity: 'base' }).compare;
console.log(['b', 'A'].sort(caseless)); // [ 'A', 'b' ]
console.log(['b', 'A'].sort()); // [ 'A', 'b' ]
Both give the same order here, but for different reasons. Plain sort puts A first because every capital comes before every lowercase letter, so it would also put Z before a. With sensitivity: 'base', the collator ignores case and accents entirely, so A comes first simply because a comes before b. You don't need to lowercase every name first.
The full solution
The panel sorts the three file names lexically and naturally, and prints what [10, 9, 1].sort() does. Press Run and compare the two orders, then read the checks underneath.
const files = ['file10.txt', 'file9.txt', 'file1.txt'];
const lexical = [...files].sort();
const natural = [...files].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
// A collator built once is the tidier form for a list.
const naturally = new Intl.Collator('en', { numeric: true }).compare;
console.log('lexical :', lexical);
console.log('natural :', natural);
console.log('[10, 9, 1].sort() :', [10, 9, 1].sort(), '<- numbers, converted to strings first');
Output
10 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 10 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 is lexical, so 10 comes before 9', lexical, ['file1.txt', 'file10.txt', 'file9.txt']);
test('numeric collation reads the digits as a number', natural, ['file1.txt', 'file9.txt', 'file10.txt']);
test('a reusable collator gives the same order', ['b10', 'b9'].sort(naturally), ['b9', 'b10']);
test('sort with no comparator converts to strings, even for numbers', [10, 9, 1].sort(), [1, 10, 9]);
test('which is why numbers need one', [10, 9, 1].sort((a, b) => a - b), [1, 9, 10]);
test('sort mutates, so the original list was copied', files, ['file10.txt', 'file9.txt', 'file1.txt']);
test('zero-padding makes the lexical sort correct with no collator', ['file09', 'file10'].sort(), ['file09', 'file10']);
test('which is the whole reason for naming things 001, 002', ['002', '001', '010'].sort(), ['001', '002', '010']);
test('case-insensitive sorting is a sensitivity, not a toLowerCase', ['b', 'A'].sort(new Intl.Collator('en', { sensitivity: 'base' }).compare), ['A', 'b']);
test('and numeric collation leaves letters alone', ['b', 'a'].sort(naturally), ['a', 'b']);
[10, 9, 1].sort() returning [1, 10, 9] is the same lexical rule applied to numbers, because sort with no comparator converts every element to a string first. It is the most reliably surprising line in the language.
Zero-padding is the pragmatic answer when you control the names: pad to a fixed width and every plain sort, in every tool, gets the order right without knowing anything about collation. That is why log files, exports and image sequences are numbered 001.
Common mistakes
- Calling
sort()with no compare function on names with numbers.file10lands beforefile9. Use{ numeric: true }. - Calling
sort()with no compare function on numbers. It sorts them as text. Pass(a, b) => a - b. - Forgetting that
sortchanges the array. Copy it first with[...files]if you need the original order.
Try it yourself
- Sort
['Chapter 2', 'chapter 10', 'Chapter 1']naturally and ignoring case, using one collator with both options. - Write
padName(n)that turns7into'img007.jpg', and check that a plain sort orders 1 to 120 correctly. - Sort
['v1.10.0', 'v1.9.2', 'v1.2.0']naturally and check the result.