Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Intl.Collator

Compares strings by language rules — for fast alphabetical sorting.

Available since: ES2015 (Intl)

Syntax

new Intl.Collator(locales, options)

Parameters

ParameterTypeDescription
localesstringOptional. The language whose rules are used to compare strings.
optionsobjectOptional. 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, zoo

Natural 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.png

A case-insensitive comparison:

const collator = new Intl.Collator('en', { sensitivity: 'base' });
 
console.log(collator.compare('Anna', 'anna') === 0);

Output:

true

Notes

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

In the tutorial

  • Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.

Thanks for reading!

Donate to the site — we work hard for you.