Course contentsShow
← JavaScript
Lesson 2235 of 2,72346. InternationalizationFree lesson

The compare() Method

Use compare() as a comparator function for Array.sort() to achieve correct alphabetical ordering in any locale.

The compare() Method

What you'll learn: How to use compare() as a sorting function to achieve correct, locale-aware alphabetical ordering in any language.

Why compare() Matters

JavaScript's default Array.sort() uses simple Unicode code-point comparison, which fails spectacularly for non-English text. Spanish "ñ" might sort incorrectly, German "ö" can end up in the wrong place, and accented characters rarely behave as native speakers expect. The compare() method from an Intl.Collator instance solves this by applying proper linguistic sorting rules.

Using compare() with Array.sort()

Once you've created a collator, its compare() method returns a function perfectly suited for Array.sort():

const names = ['Ödegaard', 'Olsen', 'Øberg', 'Andersson'];

// Wrong: default sort
names.sort();
// Result depends on Unicode values, not Norwegian rules

// Right: locale-aware sort
const norwegianSort = new Intl.Collator('nb-NO');
names.sort(norwegianSort.compare);
// Now sorts correctly for Norwegian: Andersson, Olsen, Ödegaard, Øberg

How It Works

The compare() method takes two strings and returns:

  • Negative number if the first comes before the second
  • Zero if they're equivalent
  • Positive number if the first comes after the second

This is exactly what Array.sort() expects from a comparator function. By passing collator.compare directly (no need to call it yourself), the array sorts according to your specified locale rules.

const germanSort = new Intl.Collator('de-DE');
const words = ['Straße', 'Strasse', 'Straßen'];
words.sort(germanSort.compare);
// Sorted according to German conventions

Key Takeaway: Pass collator.compare directly to Array.sort() for instant, locale-correct alphabetical ordering—no manual comparison logic needed.