Codectionary / Developer documentation / JavaScript

Locale-aware Sorting with Intl.Collator

Intl.Collator compares strings according to locale-sensitive collation rules. Options such as numeric and sensitivity control treatment of digit sequences and case or accent distinctions. Exact ordering can vary with locale data and runtime versions, so specify the intended locale.

Syntax

const collator = new Intl.Collator("en", { numeric: true });
items.sort(collator.compare);

Examples

Locale-aware Sorting with Intl.Collator: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: The sorted copy logs file1,file2,file10; the original remains file10,file2,file1.

const files = ["file10", "file2", "file1"];
const collator = new Intl.Collator("en", { numeric: true });
console.log([...files].sort(collator.compare).join(","));
console.log(files.join(","));
  1. Expected result: The sorted copy logs file1,file2,file10; the original remains file10,file2,file1.
  2. numeric compares digit runs numerically instead of purely lexicographically.
  3. The original is copied because sort mutates its receiver.

Best practices

  • Reuse a collator when sorting many values.
  • Do not assume compare returns exactly -1 or 1; only its sign is specified.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading