JavaScript Interview Question #50: How does Intl.Collator work in JS

What is Intl.Collator and how does it work in JS? What’s the difference between two sorts? What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

The Intl.Collator object allows you to compare strings with regard to locale and internationalization.

Normal sort compares strings character by character using ASCII codes. First, there will always appear strings that start with capital letters, and only then, the ones that stat with small letters.

console.log(['A', 'Z', 'a', 'z'].sort()); // ['A', 'Z', 'a', 'z']

Intl.Collator solves this problem and several others. For example, in German, the letter ä comes after a, and in Swedish, it’s at the very end of the alphabet, after z.

We can select the desired locale and get a sorted array of strings according to all the rules of that locale.

console.log(['b', 'a', 'z', 'ä'].sort(new Intl.Collator('de').compare));
console.log(['b', 'a', 'z', 'ä'].sort(new Intl.Collator('sv').compare));
['a', 'ä', 'b', 'z']
['a', 'b', 'z', 'ä']

ANSWER: Two sorted arrays will appear on the screen. The first will be collated according to the rules of the en locale for Intl.Collator. The second sorting of strings will be case-sensitive. At the beginning, there will be words starting with a capital letter, and words with small letters at the end.

['America', 'apple', 'bloom', 'Boston', 'zebra']
['America', 'Boston', 'apple', 'bloom', 'zebra']

19