Sub topic 13
Comparing and Sorting Strings by Locale
This chapter assumes you know how to call Array.prototype.sort with a compare function, and that you have read the earlier chapter on UTF-16 code units and normalization. You will learn why the default ordering of strings often looks wrong to people, and how localeCompare and Intl.Collator fix it.
The Default: Code Unit Order
When you compare strings with <, >, or call sort() with no compare function, JavaScript compares the strings one UTF-16 code unit at a time. A code unit is a 16-bit number, and the string with the smaller number at the first difference counts as "less". This is fast and predictable, but it does not match how any human language orders words.
const words = ["b", "a", "C"];
console.log([...words].sort()); // ["C", "a", "b"] (code unit order)
console.log([...words].sort((x, y) => x.localeCompare(y, "en"))); // ["a", "b", "C"]
console.log("Z" < "a"); // true ("Z" is 90, "a" is 97)
console.log("\u00e9" > "z"); // true ("é" is 233, "z" is 122)All uppercase ASCII letters (65–90) come before all lowercase ones (97–122), and accented letters land after z. A list of names sorted this way puts "Zoe" before "adam" and "Émile" at the very end.
localeCompare
a.localeCompare(b, locales, options) returns a number that tells you how a orders relative to b under a language's rules:
| Return value | Meaning |
|---|---|
| Negative | `a` sorts before `b` |
| Zero | `a` and `b` are equivalent under the chosen options |
| Positive | `a` sorts after `b` |
The specification only guarantees the sign. Engines usually return -1, 0, or 1, but code that checks === -1 can break, so test with < 0, === 0, and > 0.
The return value has the shape that sort expects, so you can pass it straight through:
const names = ["Émile", "zoe", "Adam", "bea"];
names.sort((a, b) => a.localeCompare(b, "en"));
console.log(names); // ["Adam", "bea", "Émile", "zoe"]Always pass a locale
If you leave out the locales argument, the engine uses the runtime's default locale. That depends on the user's browser settings or the server's environment variables, so the same code can sort differently on two machines. Pass an explicit locale tag such as "en", "de", or "sv" unless you deliberately want the user's own locale. In that case, pass undefined so the intent is visible in the code.
Locales really do disagree. German sorts ä next to a, while Swedish treats it as a separate letter after z:
const letters = ["z", "\u00e4", "a"]; // z, ä, a
console.log([...letters].sort(new Intl.Collator("de").compare)); // ["a", "ä", "z"]
console.log([...letters].sort(new Intl.Collator("sv").compare)); // ["a", "z", "ä"]Intl.Collator
Intl.Collator is the object that does the work behind localeCompare. You create it once with a locale and options, then call its compare method as often as you like. The compare property is a getter that returns a function already bound to the collator, so you can pass collator.compare directly to sort without wrapping it.
const collator = new Intl.Collator("en", { numeric: true });
console.log(["item10", "item2"].sort(collator.compare)); // ["item2", "item10"]
console.log(collator.resolvedOptions().locale); // "en"Why reuse a collator
Each localeCompare call with locale and options may have to resolve the locale and build collation data. A sort of n items makes roughly n log n comparisons, so for large arrays a single shared collator is noticeably faster. Some engines cache this work, but you should not rely on that. A good rule: use localeCompare for a one-off comparison, and use a collator for sorting or for any loop.
The Options That Matter
The same options object works for both localeCompare and Intl.Collator.
sensitivity
sensitivity controls which differences count. It is most useful for equality checks.
| Value | `"a"` vs `"A"` | `"a"` vs `"á"` |
|---|---|---|
| `"base"` | equal | equal |
| `"accent"` | equal | different |
| `"case"` | different | equal |
| `"variant"` (default for sorting) | different | different |
console.log("a".localeCompare("A", "en", { sensitivity: "base" })); // 0
console.log("a".localeCompare("á", "en", { sensitivity: "accent" })); // negative
console.log("a".localeCompare("á", "en", { sensitivity: "case" })); // 0Case-insensitive equality with sensitivity: "base" is more reliable than comparing toLowerCase() results. It handles accents the way you choose and avoids the special cases that some languages have in case mapping.
numeric
With numeric: true, runs of digits are compared as whole numbers. That gives "natural" ordering for file names and version-like labels:
const files = ["file10.txt", "file2.txt", "file1.txt"];
console.log([...files].sort(new Intl.Collator("en", { numeric: true }).compare));
// ["file1.txt", "file2.txt", "file10.txt"]It only understands non-negative integers. The digits after a decimal point form a separate number, so "1.5" sorts before "1.10" (5 is less than 10), and a minus sign is treated as punctuation. If you need to sort real numbers, convert them with Number and subtract.
caseFirst and ignorePunctuation
caseFirst: "upper" or "lower" decides which variant comes first when two strings differ only in case. ignorePunctuation: true skips punctuation and, in most locales, whitespace when comparing.
const upperFirst = new Intl.Collator("en", { caseFirst: "upper" });
console.log(["a", "A", "b", "B"].sort(upperFirst.compare)); // ["A", "a", "B", "b"]
const loose = new Intl.Collator("en", { ignorePunctuation: true });
console.log(loose.compare("co-op", "coop")); // 0usage
usage: "sort" is the default. usage: "search" tunes the rules for deciding whether strings match rather than for ordering them. Pair it with a sensitivity setting when you build a matching function.
Sorting Records by a Field
Real data is usually objects. Call the collator on the field you sort by, and add a tiebreaker if equal keys should have a consistent order:
const people = [
{ last: "\u00d6berg", first: "Lea" }, // Öberg
{ last: "Adams", first: "Zed" },
{ last: "adams", first: "Amy" },
];
const byName = new Intl.Collator("en", { sensitivity: "base" });
const sorted = people.toSorted(
(a, b) => byName.compare(a.last, b.last) || byName.compare(a.first, b.first)
);
console.log(sorted.map((p) => `${p.first} ${p.last}`));
// ["Amy adams", "Zed Adams", "Lea Öberg"]|| works as the tiebreaker because a result of 0 is falsy. toSorted (ES2023) returns a new array. In older environments, use [...people].sort(...) instead.
Common Errors and Gotchas
Zero does not mean identical
A 0 result means the strings are equivalent under the options you chose. It does not mean ===. With sensitivity: "base", "Adams" and "adams" compare as 0. Even with the default options, canonically equivalent Unicode sequences compare as 0:
const composed = "\u00e9"; // é as one code point
const decomposed = "e\u0301"; // e + combining accent
console.log(composed === decomposed); // false
console.log(composed.localeCompare(decomposed, "en")); // 0Do not use a collator's result as a Map or Set key test. For keys, normalize with normalize("NFC") and then use ===.
Returning a boolean from the compare function
sort((a, b) => a > b) returns true or false, which convert to 1 and 0. It never returns a negative number, so the sort result is unreliable and differs between engines. Always return a signed number.
Environment differences
Collation data comes from the engine's ICU library. Browsers and modern Node.js ship full locale data, but stripped-down builds and some embedded runtimes include only a few locales and silently fall back to another one. Check what you actually got with resolvedOptions().locale, or test support with Intl.Collator.supportedLocalesOf(["sv"]). ICU updates can also change the order of a few edge cases between versions, so don't write tests that depend on exact locale order for unusual characters.
Mixing orders across systems
A database ORDER BY uses the database's collation. A binary search over data sorted by a different rule can miss items. When the order in JavaScript has to match another system's order, either use code unit order on both sides or configure both with the same locale and strength.
Exercise
You sort ["Item 20", "item 3", "Item 100"] for display in English. Case should be ignored and numbers should sort by value. Write the code and give the result.
Show answer
const c = new Intl.Collator("en", { numeric: true, sensitivity: "base" }); ["Item 20", "item 3", "Item 100"].sort(c.compare) gives ["item 3", "Item 20", "Item 100"]. The numeric option compares 3, 20, and 100 as numbers, and sensitivity "base" makes the difference between "item" and "Item" irrelevant.
Exercise
A teammate writes if (a.localeCompare(b, "en", { sensitivity: "base" }) === 0) cache.set(a, value) so that "Café" and "cafe" share one cache entry. Why doesn't this work, and what should they do instead?
Show answer
The comparison only says the two strings are equivalent. Map keys are still matched with SameValueZero, so "Café" and "cafe" stay separate entries. Derive one canonical key instead, for example key.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase(), and use that key for both set and get.
Exercise
Why does ["10.5", "10.25"].sort(new Intl.Collator("en", { numeric: true }).compare) put "10.5" first, and how do you sort these values by numeric value?
Show answer
The numeric option reads digit runs as integers, so it compares 10 with 10 and then 5 with 25, and 5 is smaller. It does not understand decimal points. Convert the strings to numbers and subtract: arr.sort((a, b) => Number(a) - Number(b)), which gives ["10.25", "10.5"].