Emmanuel Akinfulubi

JavaScriptArray

Sort an array of numbers correctly in JavaScript

Beginner · 4 min read

Sorting numbers sounds like the easiest job an array method could do. Then you call [10, 9, 1, 100, 20].sort() and get [1, 10, 100, 20, 9]. This surprises almost everyone the first time, and it shows up in real code: price lists, scores, ages, anything where the numbers have different numbers of digits.

In this tutorial you will see why the default sort gets numbers wrong, fix it with one small function, and learn the second surprise: sort changes the array you call it on. You should know arrays and arrow functions.

How the default sort compares

With nothing in its brackets, sort turns every item into a string and puts the strings in dictionary order. Dictionary order compares one character at a time, from the left.

JavaScript

console.log(['b', 'a', 'c'].sort());  // [ 'a', 'b', 'c' ]
console.log(['ab', 'b'].sort());      // [ 'ab', 'b' ]
console.log('100' < '20');            // true

'ab' comes before 'b' because the first characters are a and b, and the rest is never looked at. In the same way, '100' comes before '20' because '1' comes before '2'. For words, that is what you want. For numbers, it is wrong.

What mutate means

A method mutates an array when it changes that array instead of making a new one. sort mutates. It reorders the array in place and returns that same array, not a copy.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

25 sort compares as text by default

easy

Sort [10, 9, 1, 100, 20] with sort() and explain the result. Then sort it properly. Also check what sort did to the original array.

Stuck? Three hints, smallest first
  1. 1. With no comparator, sort converts every element to a string and compares those.
  2. 2. So ‘100’ comes before ‘20’, for the same reason ‘ab’ comes before ‘b’.
  3. 3. sort also mutates. It returns the same array, reordered.

Step 1: see the problem

Step 1

const nums = [10, 9, 1, 100, 20];
console.log([...nums].sort()); // [ 1, 10, 100, 20, 9 ]
console.log([10, 9, 1].sort()); // [ 1, 10, 9 ]

[...nums] makes a copy first, so the original isn't touched. We will come back to why that matters.

Read the result as strings and it makes sense: '1', '10', '100', '20', '9'. Each string either starts with a smaller character than the next one, or is the start of the next one, like '10' and '100'. The order is correct for text and useless for numbers.

Step 2: prove it is string order

Sort the same values written as strings:

Step 2

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

The order is identical. The default sort really is treating your numbers as text.

Step 3: sort as numbers

You fix it by passing sort a compare function. sort calls it with two items, a and b. If it returns a negative number, a goes first. Positive, b goes first. Zero, they stay as they are.

For numbers, a - b gives exactly that: negative when a is smaller.

Step 3

const nums = [10, 9, 1, 100, 20];
const asNumbers = [...nums].sort((a, b) => a - b);
console.log(asNumbers); // [ 1, 9, 10, 20, 100 ]

That is the whole fix. Whenever you sort numbers, pass (a, b) => a - b. For largest first, swap them: (a, b) => b - a.

Step 4: sort changes the original

Now the second surprise. Call sort straight on an array, without copying it first:

Step 4

const victim = [3, 1, 2];
const returned = victim.sort((a, b) => a - b);
console.log(victim);              // [ 1, 2, 3 ]
console.log(returned === victim); // true

victim itself has been reordered. And returned is not a new sorted array: it is the very same array, with two names. So const sorted = xs.sort() doesn't keep xs in its old order, even though the code reads as if it does.

This bites when another part of your program still holds xs and expects the original order, for example a list in the order the user added items. Copy first with [...xs].sort(...) when you need to keep the original.

Step 5: capitals and missing values

Two smaller things to know. Capital letters come before small ones in the default order. And undefined always goes to the end, and your compare function is never even called with it.

Step 5

console.log(['b', 'A'].sort()); // [ 'A', 'b' ]
console.log([3, undefined, 1].sort((a, b) => a - b)); // [ 1, 3, undefined ]

That is why a - b doesn't make a mess of a list with undefined in it, even though 3 - undefined would be NaN: sort sets those items aside before comparing.

The full solution

The panel sorts the same five numbers both ways, shows them as strings, and then sorts an array in place to prove the return value is the same array. Press Run and compare the two orders.

The answer

const nums = [10, 9, 1, 100, 20];

const asText = [...nums].sort();                   // the default: string order
const asNumbers = [...nums].sort((a, b) => a - b);

// What sort does to the array it is called on.
const victim = [3, 1, 2];
const returned = victim.sort((a, b) => a - b);

console.log('input        :', nums);
console.log('sort()       :', asText, '<- string order');
console.log('sort((a,b)=>a-b):', asNumbers);
console.log('why: as strings,', ['10', '9', '1', '100', '20'].sort());
console.log('--- and it mutates ---');
console.log('victim after sorting:', victim);
console.log('the return value is the same array:', returned === victim);
console.log('the classic:', [10, 9, 1].sort(), '<- 1, 10, 9');

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 compares strings', asText, [1, 10, 100, 20, 9]);
test('so 100 lands before 20', asText.indexOf(100) < asText.indexOf(20), true);
test('the classic three-element surprise', [10, 9, 1].sort(), [1, 10, 9]);
test('a numeric comparator fixes it', asNumbers, [1, 9, 10, 20, 100]);
test('sort returns the array it was called on, not a copy', returned === victim, true);
test('so the original is reordered', victim, [1, 2, 3]);
test('text sorts as you would expect', ['b', 'a', 'c'].sort(), ['a', 'b', 'c']);
test('though capitals come first, being lower code points', ['b', 'A'].sort(), ['A', 'b']);
test('undefined is moved to the end without being compared', [3, undefined, 1].sort((a, b) => a - b).map(String), ['1', '3', 'undefined']);

Two traps in one method, and both are in the assertions. The default comparator stringifies, so [10, 9, 1] sorts to [1, 10, 9] — correct string order, useless number order. And sort mutates: the array you called it on is reordered, and the return value is that same array, so const sorted = xs.sort() gives you two names for one reordered array.

The undefined assertion is a third, smaller one. undefined values are always shuffled to the end and the comparator is never called on them, which is why a comparator like a - b does not produce NaN chaos on a sparse list — it simply never sees those slots.

Common mistakes

  • Calling sort() on numbers with no compare function. You get string order: [1, 10, 9]. Always pass (a, b) => a - b.
  • Thinking sort returns a copy. It returns the same array, now reordered. Copy first if the original order matters.
  • Returning a > b from the compare function. That gives true or false, never a negative number. Return a - b instead.

Try it yourself

  1. Sort [5, 25, 100, 1] from largest to smallest.
  2. Sort ['40', '3', '200'], which are numbers stored as strings, by their numeric value.
  3. Write sortedCopy(xs) that returns a sorted copy and leaves xs alone. Check it with ===.

Keep practising

Newsletter

New writing, when it lands.

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