Sort mixed-case and accented strings in JavaScript
Intermediate · 3 min read
Sort a list of names, file names or words the default way and the result often looks wrong to a person reading it. Capital letters jump to the front. item10 comes before item2. A word starting with é ends up after zebra. Contact lists, file browsers and product menus all need text sorted the way people expect.
In this tutorial you will fix all three problems with localeCompare, a string method that compares text the way a reader would. You should know arrays, sort, and that a compare function returns a negative number when a should come first.
How the default sort orders text
Every character has a number called its code point. The default sort compares those numbers. In that numbering, all 26 capital letters come before all 26 small letters, and accented letters come after both.
console.log('A'.codePointAt(0)); // 65
console.log('a'.codePointAt(0)); // 97
console.log('B'.codePointAt(0)); // 66
console.log('é'.codePointAt(0)); // 233
console.log('a' < 'B'); // false
So 'B' (66) sorts before 'a' (97). That is correct for the numbers and wrong for a reader.
What localeCompare does
a.localeCompare(b) returns a negative number if a comes first in normal reading order, a positive number if b comes first, and zero if they match. That is exactly what a compare function must return, so you can hand it straight to sort. The word locale means a language and region, because alphabetical order differs a little between languages.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
28 Sorting text that is not plain ASCII
fairSort ['apple', 'Banana', 'cherry'], then ['item10', 'item9', 'item2'], then a word with an accent. Fix each one.
Stuck? Three hints, smallest first
- 1. The default comparator uses code point order, where every capital letter is below every lower-case one.
- 2.
localeCompareknows thataandAdiffer less thanaandb. - 3.
localeCompare(other, undefined, { numeric: true })compares digit runs as numbers.
Step 1: see the capital letter problem
const mixedCase = ['apple', 'Banana', 'cherry'];
console.log([...mixedCase].sort()); // [ 'Banana', 'apple', 'cherry' ]
Banana comes first only because it starts with a capital. [...mixedCase] copies the list first, since sort changes the array you call it on.
Step 2: fix it with localeCompare
const mixedCase = ['apple', 'Banana', 'cherry'];
console.log([...mixedCase].sort((a, b) => a.localeCompare(b))); // [ 'apple', 'Banana', 'cherry' ]
console.log(Math.sign('a'.localeCompare('B'))); // -1
localeCompare knows that a and A are the same letter, so it treats the difference between them as smaller than the difference between a and b. The second line shows it saying 'a' comes before 'B', the opposite of <. Math.sign turns the answer into -1, 0 or 1, since the exact number isn't guaranteed.
Step 3: the lower-case approach
Another fix you will see is to lower-case both words before comparing.
const mixedCase = ['apple', 'Banana', 'cherry'];
const caseInsensitive = (a, b) => a.toLowerCase().localeCompare(b.toLowerCase());
console.log([...mixedCase].sort(caseInsensitive)); // [ 'apple', 'Banana', 'cherry' ]
Same result here. Lower-casing makes Banana and banana count as exactly equal, which is handy when you want ties to keep their original order.
Step 4: numbers inside text
Now a list of numbered files.
const numbered = ['item10', 'item9', 'item2'];
console.log([...numbered].sort()); // [ 'item10', 'item2', 'item9' ]
const natural = (a, b) => a.localeCompare(b, undefined, { numeric: true });
console.log([...numbered].sort(natural)); // [ 'item2', 'item9', 'item10' ]
The default sort compares '1' with '2' and stops there, so item10 wins. localeCompare takes two more arguments. The second picks the language: undefined means "use the default". The third is a settings object, and { numeric: true } tells it to read runs of digits as whole numbers. Now 2 comes before 9, and 9 before 10. This is often called natural order, and it is what a file list should use.
Step 5: accented letters
const accented = ['zebra', 'éclair'];
console.log([...accented].sort()); // [ 'zebra', 'éclair' ]
console.log([...accented].sort((a, b) => a.localeCompare(b))); // [ 'éclair', 'zebra' ]
By code point, é is 233, which is past z (122). localeCompare knows that é is a kind of e, so éclair sorts with the other words starting with e.
Step 6: sorting a long list
localeCompare does more work than <, so it is slower. For a long list, make one Intl.Collator, an object that holds the comparison settings, and use its compare method.
const collator = new Intl.Collator(undefined, { numeric: true });
console.log(['item10', 'item9', 'item2'].sort(collator.compare)); // [ 'item2', 'item9', 'item10' ]
It sorts the same way, and the settings are prepared once instead of on every comparison.
The full solution
The panel sorts the three lists the default way and with localeCompare, side by side. Press Run and compare each pair of lines.
const mixedCase = ['apple', 'Banana', 'cherry'];
const numbered = ['item10', 'item9', 'item2'];
const accented = ['zebra', 'éclair'];
const caseInsensitive = (a, b) => a.toLowerCase().localeCompare(b.toLowerCase());
const natural = (a, b) => a.localeCompare(b, undefined, { numeric: true });
console.log('default :', [...mixedCase].sort(), '<- B before a, by code point');
console.log('locale :', [...mixedCase].sort((a, b) => a.localeCompare(b)));
console.log('lower-cased:', [...mixedCase].sort(caseInsensitive));
console.log('--- numbers inside text ---');
console.log('default :', [...numbered].sort(), '<- item10 before item2');
console.log('numeric :', [...numbered].sort(natural));
console.log('--- accents ---');
console.log('default :', [...accented].sort(), '<- é is code point 233, past z');
console.log('locale :', [...accented].sort((a, b) => a.localeCompare(b)));
console.log("'a'.localeCompare('B') =", 'a'.localeCompare('B'));
Output
9 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 9 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 puts every capital first', [...mixedCase].sort(), ['Banana', 'apple', 'cherry']);
test('localeCompare orders them as a reader would', [...mixedCase].sort((a, b) => a.localeCompare(b)), ['apple', 'Banana', 'cherry']);
test('lower-casing first works too', [...mixedCase].sort(caseInsensitive), ['apple', 'Banana', 'cherry']);
test("because localeCompare says 'a' comes before 'B'", Math.sign('a'.localeCompare('B')), -1);
test('while a code point comparison says the opposite', 'a' < 'B', false);
test('digits in text sort as text by default', [...numbered].sort(), ['item10', 'item2', 'item9']);
test('the numeric option reads the runs as numbers', [...numbered].sort(natural), ['item2', 'item9', 'item10']);
test('an accented letter sorts past z by code point', [...accented].sort(), ['zebra', 'éclair']);
test('but next to e by locale', [...accented].sort((a, b) => a.localeCompare(b)), ['éclair', 'zebra']);
The default comparator is < on strings, which is code point order: all 26 capitals sit below all 26 lower-case letters, and every accented character sits above both. That is why an untouched sort() produces a list no human would call alphabetical.
localeCompare is the fix, and its third argument is the part people miss. { numeric: true } gives you the "natural" ordering that puts item9 before item10, which is what a file list should do. It is slower than <, so for a large array build a key with Intl.Collator once and reuse it rather than calling localeCompare inside the comparator.
Common mistakes
- Using the default
sort()for names. Capitals come first and accents come last. Pass(a, b) => a.localeCompare(b). - Forgetting
{ numeric: true }for file names. Without it,item10still comes beforeitem2. - Checking for exactly
-1or1.localeCompareonly promises the sign. Compare the result with zero, or useMath.sign.
Try it yourself
- Sort
['Zainab', 'adaeze', 'Émeka', 'bola']the way a phone's contact list would. - Sort
['v1.10', 'v1.2', 'v1.9']so the versions come out in order. - Sort
['b', 'A', 'a', 'B']and see which of each pair comes first. Then try the option{ caseFirst: 'upper' }.