Sub topic 13
Comparing and Sorting Strings by Locale
This chapter assumes you know how to use array methods such as sort and map. It also assumes you have read the earlier chapter on UTF-16 and code points. JavaScript stores strings as UTF-16 code units, and that storage format affects how the default comparison works.
Why the Default Comparison Misleads
The <, > and === operators compare strings one UTF-16 code unit at a time. So does Array.prototype.sort when you call it without a comparator. Every uppercase ASCII letter (65–90) has a lower code than every lowercase letter (97–122). As a result, "Z" sorts before "a". Accented letters such as "é" (233) sort after "z" (122).
console.log("a" < "B"); // false (97 > 66)
console.log(["b", "a", "C"].sort()); // ["C", "a", "b"]
console.log(["résumé", "zebra", "apple"].sort()); // ["apple", "zebra", "résumé"]Code-unit order is fast and the same on every machine. It does not match the order a human reader expects, so use it only for internal keys, not for text you show to users.
localeCompare
str.localeCompare(other, locales, options) returns a negative number when str sorts first, zero when the two are equivalent, and a positive number when other sorts first. You can pass it straight to sort:
const words = ["b", "a", "C"];
console.log([...words].sort((x, y) => x.localeCompare(y, "en"))); // ["a", "b", "C"]
console.log("ä".localeCompare("z", "de") < 0); // true: German puts ä with a
console.log("ä".localeCompare("z", "sv") > 0); // true: Swedish puts ä after zIf you leave out the locale, the runtime's default locale is used, and your output can change from one machine to another. Pass an explicit locale whenever the order matters.
Options That Change the Rules
The sensitivity option decides which differences count:
| sensitivity | `"a"` vs `"A"` | `"a"` vs `"á"` |
|---|---|---|
| `"base"` | equal | equal |
| `"accent"` | equal | different |
| `"case"` | different | equal |
| `"variant"` (default for sort) | different | different |
console.log("a".localeCompare("A", "en", { sensitivity: "base" })); // 0The numeric: true option compares runs of digits by their numeric value. Without it, "item10" sorts before "item2" because the character "1" comes before "2".
Reusing a Comparator with Intl.Collator
Each localeCompare call may have to set up comparison rules again. When you sort a large array, create one Intl.Collator and pass its compare method instead:
const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
console.log(["item10", "item2", "Item1"].sort(collator.compare));
// ["Item1", "item2", "item10"]collator.compare is already bound to its collator, so you can pass it without wrapping it in an arrow function.
Common Errors
- Calling
sort()with no comparator on user-visible names. - Leaving out the locale, which makes results depend on the machine.
- Using
toLowerCase() === toLowerCase()to compare without case. A collator withsensitivity: "base"handles accents and locale rules correctly. - Building a new
Intl.Collatorinside the comparator, which repeats the setup cost on every comparison.
Exercise
Sort ["file20.txt", "File3.txt", "file100.txt"] in English so that case is ignored and numbers compare by value. What code do you write, and what is the result?
Show answer
Use ["file20.txt", "File3.txt", "file100.txt"].sort(new Intl.Collator("en", { numeric: true, sensitivity: "base" }).compare). The result is ["File3.txt", "file20.txt", "file100.txt"].
Exercise
Why might "ä".localeCompare("z") give different signs on two servers?
Show answer
No locale was passed, so each server uses its own default locale. German puts ä next to a (negative result), and Swedish puts it after z (positive result).