Skip to content

Sorting and formatting for the reader's language

Keep each cell's raw value, sort with a comparator for its type (a locale collator for text), and format numbers and dates for the reader when drawing. A strong answer says where the locale applies and where it doesn't.

On this page

What it is

Locale-aware sorting and formatting is the practice of keeping two things apart: the value a cell holds and the text a reader sees. The value is a number, an instant in time or a string. The text depends on the reader's language and region: German writes 123456.789 as 123.456,789, Indian English groups it as 1,23,456.789, and Egyptian Arabic uses its own digits. Dates differ in order as well: US English puts the month first, British English the day, Korean the year. If the table sorts or does arithmetic on the drawn text, those readers can get different results from the same data.

Text has no single natural order either. The Unicode Collation Algorithm compares strings on several levels, roughly letters first, then accents, then case for Latin script, and it expects each language to tailor the default table. The same letter lands in different places: in German ä sorts with a, in Swedish it comes after z, and German itself has a dictionary order and a phonebook order that disagree about ö. A collator built for the reader's locale applies the right tailoring. In the browser that is Intl.Collator, which String.prototype.localeCompare delegates to; for a large array, build one collator and pass its compare to sort, which avoids re-reading the options on each comparison.

The collator's options cover the cases a table hits most. numeric: true compares digit runs by value, so 1 < 2 < 10. sensitivity: "base" treats a, á and A as equal; it is the setting for a filter box with usage: "search", and for a sort it gives a deliberately case- and accent-insensitive grouping, with the cost that the collator no longer decides the order among strings it calls equal. caseFirst picks whether upper or lower case comes first when a locale leaves it open.

ts
type Cell =
  | { kind: 'number'; value: number }
  | { kind: 'date'; value: number }     // epoch milliseconds, an instant
  | { kind: 'text'; value: string };

const locale = doc.locale ?? navigator.language; // the document's setting, else the browser's
const collator = new Intl.Collator(locale, { numeric: true });
const numberFmt = new Intl.NumberFormat(locale);
const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: doc.timeZone });

// In this example, mixed columns order numbers, then dates, then text.
const kindRank: Record<Cell['kind'], number> = { number: 0, date: 1, text: 2 };

function compareCells(a: Cell, b: Cell): number {
  if (a.kind !== b.kind) return kindRank[a.kind] - kindRank[b.kind];
  if (a.kind === 'text' && b.kind === 'text') return collator.compare(a.value, b.value);
  const x = a.value as number, y = b.value as number;
  return x < y ? -1 : x > y ? 1 : 0; // explicit comparison, no subtraction
}

function draw(cell: Cell): string {
  switch (cell.kind) {
    case 'number': return numberFmt.format(cell.value);
    case 'date': return dateFmt.format(cell.value);
    case 'text': return cell.value;
  }
}

// Learn the locale's separators from formatToParts. Separators only: a locale
// with its own digits (Arabic-Indic, for example) needs a digit map first.
function parseNumber(text: string): number | undefined {
  const parts = new Intl.NumberFormat(locale).formatToParts(1234567.8);
  const group = parts.find((p) => p.type === 'group')?.value ?? ',';
  const decimal = parts.find((p) => p.type === 'decimal')?.value ?? '.';
  const plain = text.trim().split(group).join('').replace(decimal, '.');
  const n = Number(plain);
  return plain !== '' && Number.isFinite(n) ? n : undefined;
}

The parsing helper exists because Intl formats but doesn't parse. format() returns a string meant for eyes, and formatToParts() returns the same content as typed pieces, including a group part and a decimal part, so a program can learn which separators the locale uses and strip or swap them before Number() reads the text. That covers separators; a locale that writes its own digits, as Egyptian Arabic does, also needs the digits mapped to ASCII first. A value that fails to parse stays a string, drawn as typed, rather than becoming a silent zero.

Dates carry one more trap: a stored instant can fall on different calendar days in different time zones. The same UTC instant at 03:00 on December 20 is drawn as December 19 for a reader in Los Angeles, and Intl.DateTimeFormat with no arguments follows the runtime's default locale and time zone, which can differ between the people viewing the table. Sort on the instant and pass an explicit timeZone when the table has one, as a shared calendar does. For a reader in Japan, the locale can also pick a calendar: ja-JP-u-ca-japanese draws 2012 as year 24 of the Heisei era.

When to use it

Reach for a locale collator whenever people read the column as words: names, titles, cities, product descriptions. Pass the locale the interface is shown in rather than leaving it to the runtime default, and give a fallback list such as ["ban", "id"] when the first language may not be supported. navigator.language is the browser's own preference and is a sensible default when the document has no locale of its own.

Add numeric: true for columns that mix letters and digits, such as file names or version labels, so v2 sorts before v10. The same idea exists on the server: PostgreSQL 17 lets you create ICU collations whose language tag carries settings, kn for numeric digit handling so that id-45 compares below id-123, or ks-level1 to ignore accents and case; the documentation's examples for both are created with deterministic = false.

When the table shows one page of a larger set, sort where all the rows are. A client sort of the visible 50 rows reorders a slice and leaves the other pages unsorted relative to it. In PostgreSQL 17 the unicode collation sorts by the Unicode Collation Algorithm's default table, and a CREATE COLLATION with provider = icu and a locale such as de-DE gives a language's tailoring; the docs warn that results may change if the server is built against a different ICU version. Our advice: pick one place to sort, usually the server, and let the client show the order it was given.

Tell assistive technology what the order is. aria-sort goes on the header cell of the sorted column with ascending or descending, moves to the new header when the user sorts another column, and sits on one header at a time. It describes the order; your code still has to produce it. Pair it with a visible indicator and a caption that explains how to sort for readers who don't see the arrows.

When a string doesn't carry its own order, store the order. A Japanese name written in kanji doesn't encode its pronunciation, and lists of names are read in pronunciation order, so a collator comparing the characters can't be expected to produce the order a Japanese reader looks for. Our advice: keep a reading field (the kana for each name) and sort on that while drawing the kanji.

When not to

Don't use a locale collator for machine identifiers: hashes, SKUs, API keys, anything that must sort the same way on each machine and in each browser. A collator's order depends on the locale's tailoring and on the collation data the runtime ships, and the database docs note that ICU-based order can shift between library versions. For those columns a plain code-unit comparison is the right tool because it depends on no locale data, even though its placement of accented letters often differs from what a reader expects.

Don't format values that another program will read. A CSV export, an API payload or a clipboard copy meant for another tool should carry the stored number and a fixed date format, not 1.234,00 €. A formatted string is opaque to the receiver, and a US tool may read the German thousands separator as a decimal point. Format at the last step, for a person.

Our advice: skip building a collator for a short list. MDN recommends the explicit collator when comparing many strings; for a handful of comparisons, localeCompare with a locale argument does the same job. And be deliberate with sensitivity: "base" in a sort: it makes a and A compare equal, which is what you want for a case-insensitive grouping, but the collator then no longer decides which of the two comes first.

Compared

ApproachWhat it doesReach for it whenWhat it costs

Plain code-unit comparison

In JavaScript, orders strings by UTF-16 code units instead of a language's rules

Identifiers, hashes, anything diffed or merged across systems

One fixed order can't match both German and Swedish, which disagree about where ö goes

localeCompare(b, locale)

Delegates to a collator for one pair of strings

A short list, or a one-off comparison

Resolves the locale and options on each call

Intl.Collator reused

One collator, its compare passed to sort, with numeric or caseFirst set

Large arrays, a table column sorted on the client

Must be rebuilt when the locale changes

Database collation (PostgreSQL 17 ICU)

ORDER BY col COLLATE "de-DE-x-icu" sorts in the database with a language tailoring

The table is paginated and the server owns the order

Order can shift with the ICU version the server is built against

Separate sort key

A stored reading or rank field sorted instead of the drawn text

Japanese names in kanji, custom orders like priority labels

An extra field to collect and keep in step with the text

In a picture

Pasted: 1.234Parse with localeStored: 1234

Step 1 of 3

Pasted text becomes a stored value

Someone pastes 1.234 into a numeric column of a German-locale document. The parser learns from formatToParts that the period is the group separator, strips it and stores the number 1234. Text that fails to parse is stored as a string instead.

How to say it in an interview

The common mistake

Quiz

A table of surnames includes Ängel. A reader in Germany and a reader in Sweden each sort the column with a collator for their own locale. Where does it land?
A document is set to German. Someone pastes 1.234 into a numeric column. What should the cell store?
A table shows one page of a much larger set and the user clicks a header to sort. Where should the sort happen?
You set aria-sort="ascending" on a header cell. What changes?

Questions that use this

Hear it in

Related

Sources

  1. MDN: Intl.Collator
  2. MDN: Intl.Collator() constructor
  3. MDN: Intl.Collator.prototype.compare()
  4. MDN: String.prototype.localeCompare()
  5. MDN: Intl.NumberFormat
  6. MDN: Intl.NumberFormat.prototype.formatToParts()
  7. MDN: Intl.DateTimeFormat
  8. MDN: Intl
  9. Unicode Technical Standard #10: Unicode Collation Algorithm
  10. MDN: ARIA: aria-sort attribute
  11. ARIA Authoring Practices Guide: Sortable Table Example
  12. PostgreSQL 17 Documentation: 23.2. Collation Support
Sign in to report a mistake