Course contentsShow
← Web Development
Lesson 2777 of 2,98249. Dates, Times, and Numbers on the WebFree lesson

Intl.Collator for Sorting

Using Intl.Collator to sort strings according to locale-specific collation rules.

Intl.Collator for Sorting

You'll learn how to sort strings correctly across different languages using Intl.Collator instead of the default JavaScript sort.

The Problem with Default Sorting

JavaScript's default string comparison doesn't understand linguistic rules. The simple < or > operators (and Array.sort()) compare strings by Unicode code points, which produces incorrect ordering for many languages. For example, in German, "ä" should sort near "a", but default sorting places it after "z". In Swedish, "ö" comes after "z" at the end of the alphabet.

What Intl.Collator Does

Intl.Collator provides locale-aware string comparison that respects the sorting rules (collation) of specific languages and regions. Think of it as hiring a native speaker to alphabetize your list instead of using a robot that only knows ASCII values.

Basic Usage

// Create a collator for German
const germanCollator = new Intl.Collator('de-DE');

const words = ['Äpfel', 'Banane', 'Ananas', 'Österreich'];

// Sort using the collator's compare method
words.sort(germanCollator.compare);
// → ['Ananas', 'Äpfel', 'Banane', 'Österreich']
// (Ä sorts with A in German)

Options for Finer Control

You can customize collation behavior:

const collator = new Intl.Collator('en-US', {
  sensitivity: 'base', // ignore accents and case
  numeric: true        // "2" comes before "10"
});

['item10', 'item2', 'item1'].sort(collator.compare);
// → ['item1', 'item2', 'item10'] (numeric sorting!)

The compare method returns -1, 0, or 1, making it perfect for Array.sort().

Key Takeaway: Use Intl.Collator to sort strings according to language-specific rules, creating a compare function that produces culturally correct alphabetical ordering across locales.