liveBook · Manning

Intl.Collator

As explained in Secrets of the JavaScript Ninja, Third Edition

Intl.Collator is a JavaScript internationalization API constructor that creates locale-sensitive string comparison objects.

Sorting names for users? Comparing strings with `<` follows character codes, which can give poor results across Unicode. `Intl.Collator` creates a comparison object tailored to a locale; its `compare` method fits an array sort callback. section 10.1.4

Listing 10.9 Sorting an array
const ninjas = [
  { name: "Yoshi" },
  { name: "Yagyu" },
  { name: "Kuma" },
];
 
const collator = new Intl.Collator();  #A
 
ninjas.sort((ninja1, ninja2) =>  #B
  collator.compare(ninja1.name, ninja2.name),  #B
);  #B

console.assert(
  ninjas[0].name === "Kuma" &&
    ninjas[1].name === "Yagyu" &&
    ninjas[2].name === "Yoshi",
  "The ninjas are now in alphabetical order",
);

Create one collator, then compare the names of two objects each time `sort` calls its callback. A negative result puts the first name earlier; a positive result puts it later; zero treats them as equivalent for sorting. section 10.1.4

A collator can be configured for casing, numbers, and punctuation. Reuse it across comparisons: `localeCompare` provides similar functionality but repeats collator initialization on each call. Remember that `sort` changes the original array; ES2023’s `toSorted` avoids that mutation. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains comparator return values and collator reuse, but defers detailed configuration options to MDN.
Examples
Sorts an array of objects by name using one collator and a sort callback.
What it assumes
Assumes familiarity with arrays and callbacks while explaining what comparator return values mean.
What you can do after
Apply it via Intl.Collator to sort names while reusing one locale-sensitive comparison object.
How it connects
Connects Intl.Collator to Unicode, array sorting, localeCompare, and toSorted.

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.