Intl.Collator
The Intl.Collator object enables language-sensitive string comparison. It is useful for sorting strings in a way that respects the rules of a specific language (e.g., handling accents, specific alphabet orders).
1. Basic Usage
The compare method of a Collator instance returns a number indicating how string1 compares to string2 according to the sort order of the Collator object.
- Negative number:
string1comes beforestring2. - Positive number:
string1comes afterstring2. - Zero: They are considered equal.
const collator = new Intl.Collator('en-US');
console.log(collator.compare('a', 'c')); // -1 (or negative)
console.log(collator.compare('c', 'a')); // 1 (or positive)
console.log(collator.compare('a', 'a')); // 0
2. Sorting Arrays
This is the most common use case. Instead of the default ASCII sort, you can use a collator for correct alphabetical sorting.
const names = ['Zebra', 'Álvaro', 'Aaron', 'älg'];
// Default sort (ASCII based)
console.log([...names].sort());
// ["Aaron", "Zebra", "älg", "Álvaro"] (Incorrect for many languages)
// Collator sort
const collator = new Intl.Collator('sv'); // Swedish
console.log([...names].sort(collator.compare));
// ["Aaron", "Zebra", "Álvaro", "älg"] (Correct in Swedish)
const germanCollator = new Intl.Collator('de');
console.log([...names].sort(germanCollator.compare));
// ["Aaron", "älg", "Álvaro", "Zebra"] (Correct in German)
3. Numeric Sorting
When sorting strings that contain numbers (like filenames), standard sorting can be annoying ("1", "10", "2"). Intl.Collator handles this with the numeric option.
const files = ['file10.txt', 'file2.txt', 'file1.txt'];
// Standard sort
console.log(files.sort());
// ["file1.txt", "file10.txt", "file2.txt"]
// Numeric Collator
const numericCollator = new Intl.Collator(undefined, { numeric: true });
console.log(files.sort(numericCollator.compare));
// ["file1.txt", "file2.txt", "file10.txt"]
4. Sensitivity
You can control how differences in case or accents are treated.
base: Only strings that differ in base letters compare as unequal. (a == A == á)accent: Only strings that differ in base letters or accents and other diacritic marks compare as unequal. (a == A != á)case: Only strings that differ in base letters or case compare as unequal. (a != A, a == á)variant: Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. (default)
programming/javascript/vanilla/javascript programming/javascript/vanilla/intl-numberformat programming/javascript/vanilla/intl-datetimeformat