Natural Sort With Numeric Order

Sort file names and labels naturally so item2 comes before item10, using Intl.Collator with a deterministic tie-break.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
export function createNaturalComparator(locale = "en", options = {}) {
  const collator = new Intl.Collator(locale, {
    numeric: true,
    sensitivity: "base",
    ...options,
  });
  return (left, right) => {
    const a = String(left);
    const b = String(right);
    return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
  };
}

export const naturalCompare = createNaturalComparator();

export function naturalSort(values, compare = naturalCompare) {
  if (!Array.isArray(values)) throw new TypeError("values must be an array");
  return [...values].sort(compare);
}

Inside the snippet

Count the functions createNaturalComparator and naturalSort as the entire surface area of Natural Sort With Numeric Order.

When the guard condition holds, TypeError is thrown rather than a bogus value returned.

A fresh value is allocated for the result; the arguments stay untouched.

Putting it to use

The main signature reads export function createNaturalComparator(locale = "en", options = {})

Treat createNaturalComparator as the API: import it, and ignore the supporting code.

Core lines

return [...values].sort(compare);
return (left, right) => {
const a = String(left);
const b = String(right);
return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
};
if (!Array.isArray(values)) throw new TypeError("values must be an array");

Interactive Tools for This Topic

FAQ

Does `createNaturalComparator` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Does the code validate its input?
The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `createNaturalComparator`, `naturalSort` at load time.