Sub topic 6
Sorting Strings for Humans: localeCompare and Intl.Collator
This chapter assumes you know how comparator functions work (negative, zero, or positive return values) and that sort() without a comparator orders elements by UTF-16 code units. Here you will make string sorting match what a human reader expects.
Why Code-Unit Order Fails People
Code-unit order puts every uppercase ASCII letter before every lowercase one. Accented letters land after z, because their code units are larger. A list of names or product titles sorted this way looks broken to most readers.
const words = ['banana', 'apple', 'Cherry', 'éclair'];
console.log(words.toSorted());
// ['Cherry', 'apple', 'banana', 'éclair']
console.log(words.toSorted((a, b) => a.localeCompare(b, 'en')));
// ['apple', 'banana', 'Cherry', 'éclair']Cherry jumps to the front because C is code unit 67 and a is 97. éclair goes last because é is 233. The localeCompare version follows the language's collation rules. Collation is the set of rules a language uses to put text in order, so here letters compare as letters first, and case and accents only break ties.
localeCompare
a.localeCompare(b, locales, options) returns a negative number if a sorts before b, a positive number if after, and 0 if the two are equal. That matches the comparator contract exactly, so you can return it directly.
The locales argument matters. The same letters can sort differently from one language to another:
const letters = ['z', 'ä', 'a'];
console.log(letters.toSorted((a, b) => a.localeCompare(b, 'de')));
// ['a', 'ä', 'z'] German treats ä as a variant of a
console.log(letters.toSorted((a, b) => a.localeCompare(b, 'sv')));
// ['a', 'z', 'ä'] Swedish puts ä after zIf you pass undefined, the runtime's default locale is used, and that can differ between a developer's laptop, a CI server, and a user's browser. When the output must be the same everywhere, such as in tests or exported files, pass an explicit locale.
Intl.Collator for Repeated Comparisons
Each localeCompare call with locale or options arguments may have to resolve those settings again. A sort makes roughly n log n comparisons, so on large arrays that repeated work adds up. Intl.Collator resolves the settings once. Its compare method is already bound to the collator, so you can pass it straight to sort.
const collator = new Intl.Collator('en', { sensitivity: 'base' });
const people = [
{ name: 'émile' },
{ name: 'Bea' },
{ name: 'adam' }
];
const byName = people.toSorted((a, b) => collator.compare(a.name, b.name));
console.log(byName.map(p => p.name)); // ['adam', 'Bea', 'émile']
const names = ['Zoe', 'ali', 'Ben'];
names.sort(collator.compare);
console.log(names); // ['ali', 'Ben', 'Zoe']Create the collator once, outside loops and render functions, and reuse it.
Useful Options
Both localeCompare and Intl.Collator accept the same options object.
| Option | Values | Effect |
|---|---|---|
| `sensitivity` | `'base'`, `'accent'`, `'case'`, `'variant'` | Which differences count. `'base'` treats `a`, `A`, and `á` as equal. `'accent'` treats `a` and `A` as equal but not `a` and `á`. |
| `numeric` | `true` / `false` | Compares digit runs by value, so `item2` sorts before `item10`. |
| `caseFirst` | `'upper'`, `'lower'`, `'false'` | Decides which case wins a tie between letters that are otherwise equal. |
| `ignorePunctuation` | `true` / `false` | Skips punctuation and whitespace while comparing. |
console.log('a'.localeCompare('A', 'en', { sensitivity: 'base' })); // 0
console.log('a'.localeCompare('á', 'en', { sensitivity: 'accent' }) !== 0); // true
const upperFirst = new Intl.Collator('en', { caseFirst: 'upper' });
console.log(['apple', 'Apple'].sort(upperFirst.compare)); // ['Apple', 'apple']Common Mistakes
- Using
<and>on strings. These operators compare code units, which gives you the default order again. - Building a new collator per comparison. Writing
(a, b) => new Intl.Collator('en').compare(a, b)throws away the performance benefit of a collator. - Using locale order for lookups. Binary search and deduplication need the same comparator that sorted the data. If you sort with a collator, search with that same collator.
- Expecting identical output on every runtime. Collation data comes from the engine's ICU library, and it can vary slightly between versions.
Exercise
You have const tags = ['Résumé', 'resume', 'Report', 'apple']. Write one line that sorts it in English order, treating case and accents as irrelevant, without mutating tags. What happens to 'Résumé' and 'resume'?
Show answer
const sorted = tags.toSorted(new Intl.Collator('en', { sensitivity: 'base' }).compare); The result starts with 'apple', followed by 'Report'. 'Résumé' and 'resume' compare as equal (0), and because sort is stable they stay in their original relative order: ['apple', 'Report', 'Résumé', 'resume'].
Exercise
Why can names.sort((a, b) => a.localeCompare(b)) produce different results in a test on CI than on your machine, and how do you fix it?
Show answer
With no locale argument, the runtime's default locale is used, and it can differ between environments. Pass an explicit locale, for example a.localeCompare(b, 'en'), or use a shared new Intl.Collator('en').