Intl.Collator
Learn locale-aware sorting and comparison with Intl.Collator.
Intl.Collator
Intl.Collator compares and sorts strings by locale. The default Array.prototype.sort uses ASCII order, so letters like 'é' and 'ñ' land in the wrong place for many languages. With Intl.Collator('en') you sort the English alphabet correctly; the compare method takes two strings and returns -1, 0 or 1. You can pass the result directly as a callback to Array.sort. Options control letter sensitivity, numeric sorting and punctuation.
The compare method and options
The compare method takes two strings; it returns a negative number when the second string comes first, zero when equal, and a positive number otherwise. Pass collator.compare directly to Array.sort to sort. The sensitivity option controls letter awareness: 'base' ignores case, 'accent' counts accents, 'case' only case, 'variant' is the strict default. With numeric: true, 'item2' sorts before 'item10'.
Exercise Sort names in Turkish
Create an Intl.Collator for the 'tr-TR' locale. Set sensitivity to 'base'. Sort the names array with collator.compare.
Show example solution
1. Create with const collator = new Intl.Collator('tr-TR', { sensitivity: 'base' }).
2. Sort with names.sort(collator.compare).
Example solution:
const collator = new Intl.Collator('tr-TR', { sensitivity: 'base' });
names.sort(collator.compare);
Test yourself
-
Why use Intl.Collator instead of Array.sort?
- Because it is faster
- Because it applies the locale-specific letter order
- Because it uses less memory
- Because it reverses the array
Show answer
Because it applies the locale-specific letter order — Correct. Collator applies locale-specific sorting; ASCII order misplaces letters in many languages.
-
Ignore letter case
const c = new Intl.Collator('tr-TR', { sensitivity: ____ });Show answer
const c = new Intl.Collator('tr-TR', { sensitivity: 'base' }); -
Match Collator options to their meaning
- sensitivity
- Letter sensitivity
- numeric
- Numeric sorting
- caseFirst
- Case priority
- ignorePunctuation
- Ignore punctuation