CodePark/ questions / The Intl APIs
START PRACTICINGPRACTICE
Frontend question · Internationalization › The Intl APIs

What do the two lines print?

const words = ["zebra", "Äpfel", "apple"];
console.log([...words].sort());
console.log([...words].sort(new Intl.Collator("de").compare));
["apple", "zebra", "Äpfel"] and ["Äpfel", "apple", "zebra"]

The default sort() compares UTF-16 code unit numbers. "Ä" is U+00C4, which is bigger than every plain ASCII letter, so "Äpfel" goes last. Intl.Collator("de") sorts like a German reader. It treats "Ä" as an "A" with an accent, so "Äpfel" is compared like "apfel". Its third letter "f" comes before the "p" in "apple", so it comes first.

"
["apple", "Äpfel", "zebra"] twice" is the tempting wrong answer. It assumes the default sort knows about accents, but it doesn't. Use Intl.Collator (or localeCompare) for any list a user reads. Its numeric: true option also sorts "item2" before "item10".