Sort strings alphabetically with localeCompare in JavaScript
Intermediate · 4 min read
Sorting a list of names sounds like a one-word job: call sort(). Then a user called Ölaf or ándre signs up, and their names land at the bottom of the list, after Zoe. Nobody reading the list would put them there.
In this tutorial you will sort the same names twice, once with plain sort() and once with localeCompare, and see exactly why the results differ. You will also meet two useful options: one that ignores accents and one that reads numbers inside text as numbers. You should know how to call sort on an array and what a compare function is roughly for. Both are explained again below.
What plain sort() compares
With no compare function, sort() turns every item into a string and orders them by their code units, the numbers JavaScript uses to store each character. For plain English letters that looks alphabetical, but with two catches:
- Every capital letter (65 to 90) has a smaller number than every lowercase letter (97 to 122). So
Zcomes beforea. - Accented letters have much bigger numbers.
Öis 214 andáis 225, so both land afterz.
What localeCompare does
a.localeCompare(b, 'en') compares two strings the way a dictionary for that language would. It returns a negative number if a comes first, a positive number if b comes first, and 0 if they are equal. That is exactly the shape sort wants from a compare function, so you can pass it straight in.
The 'en' is a locale, a language code. Collation rules differ between languages, so naming one makes the order predictable.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
45 Sorting text a reader would recognise
fairSort ['Ölaf', 'Zoe', 'Ada', 'ándre'] twice: with the default comparison and with localeCompare. Explain the difference.
Stuck? Three hints, smallest first
- 1.
sort()with no comparator compares UTF-16 code units. - 2. Accented letters have high code points, so they land after Z.
- 3.
localeCompareuses collation rules, which put each accented letter next to its base letter.
Step 1: the default sort
const names = ['Ölaf', 'Zoe', 'Ada', 'ándre'];
const byCodeUnit = [...names].sort();
console.log(byCodeUnit); // [ 'Ada', 'Zoe', 'Ölaf', 'ándre' ]
[...names] makes a copy first, because sort changes the array it is called on. The two accented names are pushed to the end, for the reason above: their first letters have big code numbers.
Step 2: sort with localeCompare
const names = ['Ölaf', 'Zoe', 'Ada', 'ándre'];
const byLocale = [...names].sort((a, b) => a.localeCompare(b, 'en'));
console.log(byLocale); // [ 'Ada', 'ándre', 'Ölaf', 'Zoe' ]
console.log(names[0]); // 'Ölaf'
Now ándre sits next to Ada, and Ölaf comes before Zoe, just as a reader expects. The last line shows that the original list is untouched, because we sorted a copy.
Step 3: what about case?
console.log(['b', 'A', 'a', 'B'].sort()); // [ 'A', 'B', 'a', 'b' ]
const sorted = ['b', 'A', 'a', 'B'].sort((x, y) => x.localeCompare(y, 'en'));
console.log(sorted.map((s) => s.toLowerCase())); // [ 'a', 'a', 'b', 'b' ]
The default sort puts all the capitals first. localeCompare keeps each letter's two cases together, so both as come before both bs. (The second line lowercases the result only to show the grouping clearly.)
Step 4: reading the return value
console.log('a'.localeCompare('a')); // 0
console.log('e'.localeCompare('é', 'en') !== 0); // true
console.log('e'.localeCompare('é', 'en', { sensitivity: 'base' })); // 0
Equal strings give 0. By default an accent still counts as a difference, so e and é are not equal, but they sort side by side. The sensitivity: 'base' option tells the comparison to look only at base letters, so e and é count as the same. That is handy for search.
Step 5: numbers inside text
Strings compare one character at a time, so '10' < '9' is true: the first characters are 1 and 9, and 1 comes first. The numeric option fixes that:
console.log('10' < '9'); // true
console.log('10'.localeCompare('9', 'en') < 0); // true
console.log('10'.localeCompare('9', 'en', { numeric: true }) > 0); // true
Without the option, localeCompare agrees with < and puts 10 first. With numeric: true, runs of digits are read as numbers, so 10 comes after 9. Exercise 52 uses this for file names.
Step 6: a collator for long lists
localeCompare may set up its language rules again on every call. For a big list, build an Intl.Collator once and use its compare function:
const names = ['Ölaf', 'Zoe', 'Ada', 'ándre'];
const compare = new Intl.Collator('en').compare;
console.log([...names].sort(compare)); // [ 'Ada', 'ándre', 'Ölaf', 'Zoe' ]
Same order as Step 2, with the setup done once.
The full solution
The panel sorts the names both ways and prints the two '10' against '9' comparisons. Press Run to see the two orders, then read the checks underneath.
const names = ['Ölaf', 'Zoe', 'Ada', 'ándre'];
const byCodeUnit = [...names].sort();
const byLocale = [...names].sort((a, b) => a.localeCompare(b, 'en'));
console.log('by code unit :', byCodeUnit, '<- accents pushed to the end');
console.log('by locale :', byLocale);
console.log("'10' vs '9' as text :", '10' < '9');
console.log("'10' vs '9', numeric :", '10'.localeCompare('9', 'en', { numeric: true }) > 0);
Output
11 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 11 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 uses code units, so accents land at the end', byCodeUnit, ['Ada', 'Zoe', 'Ölaf', 'ándre']);
test('localeCompare puts them where a reader expects', byLocale, ['Ada', 'ándre', 'Ölaf', 'Zoe']);
test('code-unit sorting also separates the cases', ['b', 'A', 'a', 'B'].sort(), ['A', 'B', 'a', 'b']);
test('while locale sorting keeps each letter together', ['b', 'A', 'a', 'B'].sort((x, y) => x.localeCompare(y, 'en')).map((s) => s.toLowerCase()), ['a', 'a', 'b', 'b']);
test('localeCompare returns 0 for equal strings', 'a'.localeCompare('a'), 0);
test('an accent is a difference at the default sensitivity', 'e'.localeCompare('é', 'en') !== 0, true);
test('but not at sensitivity base', 'e'.localeCompare('é', 'en', { sensitivity: 'base' }), 0);
test('numeric collation compares digit runs as numbers', '10'.localeCompare('9', 'en', { numeric: true }) > 0, true);
test('without it, 10 sorts before 9', '10'.localeCompare('9', 'en') < 0, true);
test('which is the same answer the < operator gives', '10' < '9', true);
test('sorting a copy leaves the original alone', names[0], 'Ölaf');
The default sort is not "alphabetical", it is "by code unit", and the two agree only for unaccented ASCII of a single case. Anything shown to a user should go through localeCompare or an Intl.Collator.
Use a collator rather than localeCompare when sorting a list. localeCompare may construct the collation data on every call; new Intl.Collator('en').compare builds it once and is a drop-in comparator. Exercise 52 uses it.
Common mistakes
- Calling
sort()with no compare function on names. It sorts by code unit, so accents go last and capitals go first. Pass alocaleComparecomparator. - Sorting the original array by accident.
sortchanges the array in place. Copy it first with[...names]. - Expecting
localeCompareto return exactly-1or1. It only promises a negative or positive number. Check< 0or> 0.
Try it yourself
- Sort
['éclair', 'Eagle', 'echo']with the default sort and withlocaleCompare, and explain each order. - Write a search that finds
'Ölaf'when the user types'olaf', usingsensitivity: 'base'. - Sort
['item 2', 'item 10', 'item 1']so that 10 comes last.