Intl.Collator
Compares strings by language rules — for fast alphabetical sorting.
Available since: ES2015 (Intl)
Syntax
new Intl.Collator(locales, options)Parameters
| Parameter | Type | Description |
|---|---|---|
| locales | string | Optional. The language whose rules are used to compare strings. |
| options | object | Optional. numeric: true for numbers inside strings; sensitivity: base to ignore case and accents. |
Return value
Intl.CollatorAn object with a compare(a, b) method.
Examples
Language-aware sorting:
const collator = new Intl.Collator('de');
const words = ['Zebra', 'äpfel', 'Apfel', 'zoo'];
console.log(words.sort(collator.compare).join(', '));Output:
Apfel, äpfel, Zebra, zooNatural sorting of file names:
const collator = new Intl.Collator(undefined, { numeric: true });
console.log(['img12.png', 'img2.png', 'img1.png'].sort(collator.compare).join(', '));Output:
img1.png, img2.png, img12.pngA case-insensitive comparison:
const collator = new Intl.Collator('en', { sensitivity: 'base' });
console.log(collator.compare('Anna', 'anna') === 0);Output:
trueNotes
It does the same as localeCompare() but is faster for large arrays: the language rules are loaded once. The compare method can be passed to sort() directly.
See also
- String.prototype.localeCompare — Compares strings by language rules — for alphabetical sorting.
- Array.prototype.sort — Sorts the elements of an array.
- Array.prototype.toSorted — Returns a sorted copy of an array without changing the original.
In the tutorial
- Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.