Emmanuel Akinfulubi

JavaScriptBasic

Natural sort of strings with numbers in JavaScript

Advanced · 4 min read

Sort a list of labels like Hall 1, Hall 2 and Hall 10 in JavaScript and you get a surprise: Hall 10 comes before Hall 2. File names, invoice numbers, seat numbers and version labels all have this problem. The order people expect, where 2 comes before 10, is called natural sort.

In this tutorial you will write a comparator called natural that sorts labels with numbers in them the way a person would. You need to know arrays and functions. How sort compares things, and the small regular expression we use, are explained below.

Why the default sort gets it wrong

When you call sort() with nothing inside the brackets, JavaScript turns every item into a string and compares the strings one character at a time, like words in a dictionary.

JavaScript

console.log(['Hall 10', 'Hall 2', 'Hall 1'].sort()); // [ 'Hall 1', 'Hall 10', 'Hall 2' ]
console.log([10, 9, 100].sort());                    // [ 10, 100, 9 ]

Comparing 'Hall 10' with 'Hall 2', the first five characters match. Then it compares '1' with '2', and '1' is smaller, so 'Hall 10' wins. The rest of the number is never looked at. Even plain numbers suffer: 10 and 100 both start with '1', so they land before 9.

Comparators in one minute

To change the order, pass sort a comparator: a function that gets two items, a and b, and returns a number.

  • A negative number means "a goes first".
  • A positive number means "b goes first".
  • Zero means "they are equal".

For numbers, subtracting does all three at once:

JavaScript

console.log([10, 9, 100].sort((x, y) => x - y)); // [ 9, 10, 100 ]

Our job is to write a comparator like that for labels that mix text and numbers.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

143 Sort labels that have numbers in them

hard

['Hall 10', 'Hall 2', 'Hall 1'] sorted the ordinary way puts Hall 10 before Hall 2. Write a comparator that splits each label into runs of digits and runs of anything else, and compares the digit runs as numbers.

Stuck? Three hints, smallest first
  1. 1. Default sort compares strings, so '10' < '2' because '1' < '2'.
  2. 2. Break each label into chunks: digits together, non-digits together.
  3. 3. Compare chunk by chunk; when both are digit chunks, compare Number(a) - Number(b).

Step 1: split a label into chunks

The plan is to cut each label into pieces: runs of digits, and runs of everything else. A regular expression (a pattern for matching text) does the cutting.

Step 1

const chunksOf = (text) => String(text).toLowerCase().match(/\d+|\D+/g) || [];
console.log(chunksOf('Hall 10'));   // [ 'hall ', '10' ]
console.log(chunksOf('Room 2-10')); // [ 'room ', '2', '-', '10' ]
console.log(chunksOf(''));          // []

Read /\d+|\D+/g piece by piece. \d is any digit and \D is anything that isn't a digit. + means "one or more in a row". | means "or". The g at the end means "find every match, not only the first". So match returns a list of digit runs and non-digit runs, in order.

match returns null when nothing matches, which happens for an empty string. || [] swaps that null for an empty array. toLowerCase() makes Hall and HALL compare the same.

Step 2: tell a number chunk from a text chunk

Step 2

const isDigits = (chunk) => chunk[0] >= '0' && chunk[0] <= '9';
console.log(isDigits('10'));    // true
console.log(isDigits('hall ')); // false

A chunk is either all digits or no digits, so its first character is enough to tell which kind it is.

Step 3: compare chunk by chunk

Now walk both lists of chunks side by side. Skip chunks that are the same. At the first difference, decide:

Step 3

const chunksOf = (text) => String(text).toLowerCase().match(/\d+|\D+/g) || [];
const isDigits = (chunk) => chunk[0] >= '0' && chunk[0] <= '9';
function natural(a, b) {
  const left = chunksOf(a);
  const right = chunksOf(b);
  const shared = Math.min(left.length, right.length);
  for (let i = 0; i < shared; i++) {
    if (left[i] === right[i]) continue;
    if (isDigits(left[i]) && isDigits(right[i])) return Number(left[i]) - Number(right[i]);
    return left[i] < right[i] ? -1 : 1;
  }
  return left.length - right.length;
}
console.log(natural('Hall 2', 'Hall 10')); // -8: Hall 2 goes first
console.log(natural('Hall 02', 'Hall 2')); // 0: the same number

continue jumps to the next chunk. When both chunks are digits, Number turns them into real numbers and subtracting gives the comparator answer, just like in the numbers example. That's the whole fix: 2 - 10 is -8, so Hall 2 comes first. It also means 02 and 2 count as equal.

When the chunks are text, we can't subtract: 'a' - 'b' is NaN, which isn't negative, positive or zero. So we compare with < and return -1 or 1 ourselves.

Step 4: one label is the start of the other

What about Hall 2 and Hall 2 upper? Every chunk they share is the same, so the loop finishes without returning. The last line handles that: left.length - right.length is negative when a has fewer chunks, so the shorter label goes first.

Step 4

const chunksOf = (text) => String(text).toLowerCase().match(/\d+|\D+/g) || [];
console.log(chunksOf('Hall 2').length);       // 2
console.log(chunksOf('Hall 2 upper').length); // 3

Step 5: sort a copy

sort changes the array you call it on, and returns that same array. To keep the original order, copy first with [...list]:

Step 5

const chunksOf = (text) => String(text).toLowerCase().match(/\d+|\D+/g) || [];
const isDigits = (chunk) => chunk[0] >= '0' && chunk[0] <= '9';
function natural(a, b) {
  const left = chunksOf(a);
  const right = chunksOf(b);
  const shared = Math.min(left.length, right.length);
  for (let i = 0; i < shared; i++) {
    if (left[i] === right[i]) continue;
    if (isDigits(left[i]) && isDigits(right[i])) return Number(left[i]) - Number(right[i]);
    return left[i] < right[i] ? -1 : 1;
  }
  return left.length - right.length;
}
const halls = ['Hall 10', 'Hall 2', 'Hall 1', 'Hall 20', 'Hall 3'];
console.log([...halls].sort(natural).join(', ')); // Hall 1, Hall 2, Hall 3, Hall 10, Hall 20
console.log(halls[0]);                             // Hall 10: the original is untouched
console.log(['Room 2-10', 'Room 2-9', 'Room 10-1'].sort(natural).join(', ')); // Room 2-9, Room 2-10, Room 10-1

The last line shows that every number in a label is compared as a number, not only the first one.

The full solution

The answer panel has chunksOf, isDigits and natural, and prints the halls sorted both ways. The checks cover the default sort, mixed case, leading zeros, prefixes, labels with two numbers, and the fact that sort changes the original. Press Run to see the output.

The answer

const chunksOf = (text) => String(text).toLowerCase().match(/\d+|\D+/g) || [];
const isDigits = (chunk) => chunk[0] >= '0' && chunk[0] <= '9';

function natural(a, b) {
  const left = chunksOf(a);
  const right = chunksOf(b);
  const shared = Math.min(left.length, right.length);
  for (let i = 0; i < shared; i++) {
    if (left[i] === right[i]) continue;
    if (isDigits(left[i]) && isDigits(right[i])) return Number(left[i]) - Number(right[i]);
    return left[i] < right[i] ? -1 : 1;
  }
  return left.length - right.length;               // one is a prefix of the other
}

const halls = ['Hall 10', 'Hall 2', 'Hall 1', 'Hall 20', 'Hall 3'];
console.log('default: ', [...halls].sort().join(', '));
console.log('natural: ', [...halls].sort(natural).join(', '));
console.log('chunks of "Hall 10":', JSON.stringify(chunksOf('Hall 10')));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the default sort is lexicographic, so 10 lands before 2', [...halls].sort(), ['Hall 1', 'Hall 10', 'Hall 2', 'Hall 20', 'Hall 3']);
test('the comparator fixes it', [...halls].sort(natural), ['Hall 1', 'Hall 2', 'Hall 3', 'Hall 10', 'Hall 20']);
test('a label splits into text and number chunks', chunksOf('Hall 10'), ['hall ', '10']);
test('numbers alone have the same problem, and need the same treatment', [[10, 9, 100].sort(), [10, 9, 100].sort((x, y) => x - y)], [[10, 100, 9], [9, 10, 100]]);
test('case is folded, so lower and upper interleave properly', ['hall 3', 'Hall 10', 'HALL 2'].sort(natural), ['HALL 2', 'hall 3', 'Hall 10']);
test('leading zeros compare as equal numbers', [natural('Hall 02', 'Hall 2'), Number('02')], [0, 2]);
test('a shorter label that is a prefix comes first', ['Hall 2 upper', 'Hall 2'].sort(natural), ['Hall 2', 'Hall 2 upper']);
test('several numbers in one label are each compared as numbers', ['Room 2-10', 'Room 2-9', 'Room 10-1'].sort(natural), ['Room 2-9', 'Room 2-10', 'Room 10-1']);
test('and sort mutates, which is why every check above copies first', (() => { const original = ['b', 'a']; const returned = original.sort(); return [original, returned === original]; })(), [['a', 'b'], true]);

sort with no comparator converts everything to strings and compares them character by character, which is why [10, 9, 100] comes back as [10, 100, 9]. That is not a quirk to work around once; it is the default, and every sort of anything numeric needs a comparator.

The natural comparator is the same idea applied to mixed text: split into digit and non-digit runs, then compare like with like. Returning Number(a) - Number(b) for digit chunks is what puts Hall 2 before Hall 10, and returning -1 or 1 for text chunks avoids the trap of subtracting strings. The fallback left.length - right.length handles one label being a prefix of another.

Two things to know before shipping it. sort mutates the array it is called on and returns that same array, so [...list].sort(...) is the habit unless you meant to reorder the original. And for human names, especially with accents, a.localeCompare(b) is the right tool — it knows that é sorts with e, which no amount of chunking will tell you. This comparator is for labels with numbers, not for a phone book.

Common mistakes

  • Sorting numbers without a comparator. [10, 9, 100].sort() gives [10, 100, 9]. Any numeric sort needs (x, y) => x - y.
  • Subtracting text chunks. 'a' - 'b' is NaN, and sort can't use it. Return -1 or 1 for text.
  • Sorting the original by accident. sort reorders the array in place. Copy with [...list] unless you meant to change it.

Try it yourself

  1. Sort ['img12.png', 'img10.png', 'IMG2.png'] with natural. Which comes first, and why does the capital letter not matter?
  2. Write a descending version without writing a new comparator. Hint: swap a and b.
  3. Try a.localeCompare(b, undefined, { numeric: true }) as the comparator on the halls. Does it give the same order?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.