Dev Helpers
← Back

Sort localized options with a collator

Sort localized options with a collator. Start with typed records and inspect the inferred result.

Open this example in the interactive library

Source code

type Row = { key: string; en: string; fr: string };
const rows: Row[] = [
  { key: "home", en: "Home", fr: "Accueil" },
  { key: "save", en: "Save", fr: "Enregistrer" },
  { key: "help", en: "Help", fr: "" },
];
const result = rows
  .toSorted((a, b) => (a.fr || a.en).localeCompare(b.fr || b.en, "fr"))
  .map((r) => r.key);
console.log(JSON.stringify(result, null, 2));

Sample output

[
  "home",
  "save",
  "help"
]