Sort method looks sort of broken

Victor Ferreira
Aug 31, 2018 · 1 min read

If you ever tried to sort an array of numeric values in Javascript with the method sort, you probably noticed that something weird happened with the result.

Let’s take the following array of integers as an example:

[1,3,2].sort();

This will return the array [1,2,3]. Everything looks fine so far. You just successfully put all the numbers of this array in a crescent order.

The problem occurs when different numbers have the same first digit.

[1,2,10000,3].sort();

This will generate the array [1,10000,2,3]And that’s the ultimate definition of “weird”. Things get much worse when you add negative numbers.

[1,2,10000,3,-999,-99].sort();
// [-99,-999,1,10000,2,3]

Well, what is happening here is that the sort method is sorting the items in the array alphabetically.

Then what should we do?

Just pass a callback function with the sorting condition. It receives two parameters, a and b that represents two items being compared, and must return -1 if a is smaller than b , 1 if a is greater than b or 0 if they are equal.

[1,2,10000,3,-999,-99].sort((a,b) => a > b ? 1 : -1);
// [-999,-99,1,2,3,10000]

Hope it saves you some time!