Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 27, 2021 07:33 am GMT

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

javascript interview question #50

What is Intl.Collator and how does it work in JS? Whats 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, its 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']

Learn Full-Stack JavaScript


Original Link: https://dev.to/coderslang/javascript-interview-question-50-how-does-intl-collator-work-in-js-3ff8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To