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), how stable sorting allows multi-key comparisons with ||, and the difference between sort and toSorted. Here the focus is strings meant for people to read: names, titles, file names, and product labels.
Why Code-Unit Order Fails for Human Text
The default sort() converts elements to strings and compares their UTF-16 code units. A code unit is a 16-bit number, and the ordering follows those numbers. That gives a consistent result, but it does not match how people expect words to be ordered.
const words = ['rose', 'résumé', 'Resume', 'resume'];
console.log(words.toSorted());
// ['Resume', 'resume', 'rose', 'résumé']The output has these problems:
- Every uppercase letter (
A–Z, code units 65–90) sorts before every lowercase letter (97–122)."Zoo"would come before"apple". - Accented letters such as
é(code unit 233) sort afterz, sorésuméends up afterroseeven though a reader sees them both as "r-e-s…" words. - Digits are compared one character at a time, so
"item10"sorts before"item2".
A comparator written with < and > has the same flaws, because those operators compare code units too:
const naive = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
console.log(['b', 'a', 'B', 'á'].toSorted(naive)); // ['B', 'a', 'b', 'á']A common workaround is a.toLowerCase() < b.toLowerCase(). It fixes case and nothing else: accents still land after z, numbers still sort as text, and every comparison builds two new strings.
How Collation Works
Collation is the set of language-specific rules for ordering and comparing text. JavaScript exposes it through the ECMAScript Internationalization API (Intl). Engines such as V8, SpiderMonkey, and JavaScriptCore implement it with ICU and the Unicode Collation Algorithm.
The algorithm compares strings in levels. It moves to the next level only when the strings are equal at the current one:
| Level | What it compares | Example difference |
|---|---|---|
| Primary | Base letters | `a` vs `b` |
| Secondary | Accents | `a` vs `á` |
| Tertiary | Case and letter variants | `a` vs `A` |
That is why résumé sorts right after resume under collation. Their base letters are identical, so the accent decides the order at the secondary level. It is also why rose comes after both: o beats e at the primary level before accents or case are looked at.
String.prototype.localeCompare
a.localeCompare(b, locales, options) returns a negative number if a sorts before b, a positive number if after, and 0 if they are equal under the chosen rules. That matches the comparator contract, so it can be dropped straight into sort:
const words = ['rose', 'résumé', 'Resume', 'resume'];
console.log(words.toSorted((a, b) => a.localeCompare(b, 'en')));
// ['resume', 'Resume', 'résumé', 'rose']The locales argument
The locales argument is a BCP 47 language tag such as 'en', 'de', 'sv', or 'fr-CA', or an array of tags in order of preference. Languages really do disagree about order. In German, ö is an o with an accent. In Swedish, ö is a separate letter that comes after z:
const letters = ['ö', 'z', 'o'];
console.log(letters.toSorted((a, b) => a.localeCompare(b, 'de'))); // ['o', 'ö', 'z']
console.log(letters.toSorted((a, b) => a.localeCompare(b, 'sv'))); // ['o', 'z', 'ö']If you pass undefined or leave the argument out, the runtime uses its default locale. On a laptop that may be en-US, while a CI container may use something else entirely. Results can then differ between environments.
Intl.Collator: A Reusable Comparator
Intl.Collator is an object that holds a locale and a set of options, and its compare method is a ready-made comparator. compare is a getter that returns a function already bound to the collator, so you can pass it directly without wrapping it:
const collator = new Intl.Collator('en');
const words = ['rose', 'résumé', 'Resume', 'resume'];
console.log(words.toSorted(collator.compare));
// ['resume', 'Resume', 'résumé', 'rose']Why reuse matters
localeCompare with locales or options may have to resolve the locale and set up collation data on every call. Sorting n strings makes about n log n comparisons, so a 100,000-element array needs well over a million calls. Engines cache some of this work, but the specification does not require it. MDN recommends Intl.Collator when comparing large numbers of strings.
Create the collator once, outside the hot path, and reuse it:
// Created once at module load
const nameCollator = new Intl.Collator('en', { sensitivity: 'base' });
function sortByName(users) {
return users.toSorted((a, b) => nameCollator.compare(a.name, b.name));
}
console.log(sortByName([{ name: 'émile' }, { name: 'Zed' }, { name: 'adam' }]).map(u => u.name));
// ['adam', 'émile', 'Zed']localeCompare is fine for one-off comparisons and small arrays. When you sort large arrays, sort repeatedly, or need the same options in several places, use a collator.
Collator Options
Both localeCompare and Intl.Collator take the same options object. These are the options that change sorting behavior the most.
numeric: natural ordering
With numeric: true, runs of digits are compared by numeric value rather than character by character. This is often called natural sort:
const collator = new Intl.Collator(undefined, { numeric: true });
const files = ['item10', 'item2', 'item1'];
files.sort(collator.compare);
console.log(files); // ['item1', 'item2', 'item10']This handles version-like labels such as 'v1.9' and 'v1.10' too, because each digit run is compared as a separate number. It does not understand decimals, negative signs, or thousands separators. To sort actual numbers, parse them and subtract.
sensitivity: which differences count
sensitivity picks which collation levels can make two strings unequal:
| Value | `a` vs `b` | `a` vs `á` | `a` vs `A` |
|---|---|---|---|
| `'base'` | different | equal | equal |
| `'accent'` | different | different | equal |
| `'case'` | different | equal | different |
| `'variant'` | different | different | different |
const base = new Intl.Collator('en', { sensitivity: 'base' });
const accent = new Intl.Collator('en', { sensitivity: 'accent' });
console.log(base.compare('a', 'á')); // 0
console.log(base.compare('a', 'A')); // 0
console.log(accent.compare('a', 'á') === 0); // false
console.log(accent.compare('a', 'A')); // 0The default for sorting is 'variant'. When you sort, equal results matter less than you might think. Because sort has been stable since ES2019, strings that compare equal keep their original relative order. With 'base', 'Apple' and 'apple' stay in whatever order they arrived. With 'variant' the order is fully determined. Pick 'variant' when you want a deterministic order from any starting arrangement.
caseFirst: upper or lower first
When two strings differ only in case, caseFirst decides which wins: 'upper', 'lower', or 'false' (the locale default, which for English places lowercase first).
const upperFirst = new Intl.Collator('en', { caseFirst: 'upper' });
console.log(['resume', 'Resume'].toSorted(upperFirst.compare)); // ['Resume', 'resume']This only breaks ties at the case level. It does not move all capitals to the front the way code-unit order does.
usage and ignorePunctuation
usage: 'sort'(the default) is tuned for ordering lists.usage: 'search'is tuned for deciding whether strings match, and some locales apply looser matching rules in that mode.ignorePunctuation: trueskips punctuation and whitespace, so entries like'co-op'and'coop'sort next to each other.
To see what the engine actually chose after locale negotiation and option defaults, call collator.resolvedOptions():
const c = new Intl.Collator('de', { numeric: true });
console.log(c.resolvedOptions().locale); // 'de'
console.log(c.resolvedOptions().sensitivity); // 'variant'
console.log(c.resolvedOptions().numeric); // trueUsing a Collator for Matching
Collators are useful for more than sorting. A 'base' collator gives you equality that ignores accents and case, which suits user-facing lookups:
const matcher = new Intl.Collator('en', { usage: 'search', sensitivity: 'base' });
const cities = ['Zürich', 'Montréal', 'Oslo'];
const hit = cities.find(city => matcher.compare(city, 'montreal') === 0);
console.log(hit); // 'Montréal'This checks whole-string equality, not substrings. For a "contains" search that ignores accents, normalize both sides first, for example with s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase(), and then use includes.
Combining with Multi-Key and Object Sorts
A collator comparison returns the same kind of value as b.age - a.age, so it chains with || like any other key:
const collator = new Intl.Collator('en', { numeric: true });
const products = [
{ category: 'Tools', name: 'Hammer 10' },
{ category: 'garden', name: 'Hose' },
{ category: 'Tools', name: 'Hammer 2' },
{ category: 'Électronique', name: 'Radio' }
];
const sorted = products.toSorted(
(a, b) => collator.compare(a.category, b.category) || collator.compare(a.name, b.name)
);
console.log(sorted.map(p => `${p.category}/${p.name}`));
// ['Électronique/Radio', 'garden/Hose', 'Tools/Hammer 2', 'Tools/Hammer 10']Edge Cases and Gotchas
Missing values
sort moves undefined values (and holes in sparse arrays) to the end without calling your comparator. null is not treated that way. It is passed to the comparator, and null.localeCompare(...) throws a TypeError. collator.compare(null, 'a') does not throw, but it converts null to the string "null" and sorts it among the n's. Handle missing values explicitly:
const collator = new Intl.Collator('en');
const names = ['bea', null, 'Al', undefined, 'cy'];
const nullsLast = (a, b) => {
if (a == null && b == null) return 0;
if (a == null) return 1;
if (b == null) return -1;
return collator.compare(a, b);
};
console.log(names.toSorted(nullsLast)); // ['Al', 'bea', 'cy', null, undefined]Non-string values
localeCompare only exists on strings, so calling it on a number throws. collator.compare converts both arguments to strings, so collator.compare(10, 9) compares "10" with "9". Use subtraction for numbers and collation for text.
Results across environments
Collation data comes from the engine's ICU build. Newer Unicode versions sometimes change the order of rare characters, and minimal ICU builds (older Node.js releases, some embedded runtimes) may support only English. For results you can reproduce, pass an explicit locale, check resolvedOptions().locale if it matters, and avoid snapshot tests that depend on how exotic characters are ordered.
Collation is not identity
sensitivity: 'base' makes 'Resume' and 'résumé' compare equal, but they are still different strings. Do not use a base-sensitivity collator to remove duplicate primary keys, usernames, or other identifiers unless "visually similar means the same" really is your rule. Use exact equality or a defined normalization for identity.
Choosing an Approach
| Situation | Use |
|---|---|
| Machine keys, IDs, stable byte-like order | Default `sort()` or `<`/`>` comparator |
| Small list, single locale, one-off | `a.localeCompare(b, locale)` |
| Large or repeated sorts, shared options | One `Intl.Collator`, reuse `compare` |
| File names, labels with numbers | Collator with `numeric: true` |
| Accent- and case-insensitive matching | Collator with `sensitivity: 'base'` |
Exercise
You sort a list of 50,000 customer names on every page render with names.sort((a, b) => a.localeCompare(b, 'fr', { sensitivity: 'base' })). Name two problems with this code and give a corrected version.
Show answer
First, the locale and options are handled on every comparison, roughly n log n times per sort, which can be slow. Create one collator up front and reuse it. Second, 'base' sensitivity makes names that differ only in accents or case compare equal, so their order depends on input order (stable sort keeps them as they arrived). Use the default 'variant' sensitivity for a fully determined order. A third, smaller issue: sort mutates the array on every render, and toSorted avoids that. Corrected: const frCollator = new Intl.Collator('fr'); created once, then const view = names.toSorted(frCollator.compare);.
Exercise
What does ['file20.txt', 'File3.txt', 'file100.txt'].toSorted(new Intl.Collator('en', { numeric: true }).compare) return, and what would the default toSorted() return?
Show answer
With the numeric collator: ['File3.txt', 'file20.txt', 'file100.txt'], because case is only a tertiary difference and the digit runs 3, 20, 100 are compared as numbers. With the default sort: ['File3.txt', 'file100.txt', 'file20.txt'], because 'F' (70) comes before 'f' (102) and '1' comes before '2' as characters.
Exercise
An array of strings includes some null entries. Why does arr.sort((a, b) => a.localeCompare(b)) throw, while arr.sort(new Intl.Collator().compare) does not? Is the second version correct?
Show answer
sort passes null to the comparator (only undefined and holes are skipped), and null has no localeCompare method, so a TypeError is thrown. collator.compare converts its arguments to strings, so null becomes "null" and no error is raised. The second version is still wrong: the nulls sort among words starting with "n" instead of being grouped. Handle null explicitly, for example by returning 1 or -1 when either side is null before calling collator.compare.