Javascript Array.sort() - Mystery Solved

Rajat Gupta
3 min readMay 10, 2021

Ever wonder why array.sort() function does not work for integers / numbers correctly so follow this article till the end and you will have your answer.

Lets take few examples and try to understand the mysterious sort function.

Example 1: Alphabetic Sorting / String Sorting

Result:

Bravo sort function worked. But the point to note here is sort function did sorting of strings taking in consideration of first character of each element in array.

Example 2: Integer Sorting

Result:

Hmm it worked for integers as well without changing the sort function. So where is the problem, why you are reading this article. Hang on and you will get your answers.

Example 3: Integer Sort for Integer in array 0 to >10 (This will blow your mind)

Result:

Hmm why the sort function is not working in this case is it broken it worked for the above two examples perfectly but not for this one.

Mystery Solved: The reason it did not work is because sort function treats every element in the array as character and when we pass integer array it converts into character and then character is matched for sorting the array. That is why sort function does not work. More precisely it checks and compare the ascii value of first character and if first character ascii is equal it moves to next character going left to right.

So to make this work there is a need to pass compare function in the sort function.

function compare(a, b) {
// a-b for ascending sort
return a - b;

// b-a for descending sort
// return b - a;
}

This above function need to be passed inside Array.sort(compare(a, b))

ES6 syntax for sort function : Array.sort((a, b) => a - b);

Now some might be thinking what is this a - b and b - a. So, Lets understand this with and example:

Result:

Yeah Sort function is fixed. So now lets understand the compare function. Compare function can return negative, positive, and zero. So if negative is returned it means a < b, positive is returned means a > b, zero is returned means a = b. So, sort function has three different argument :

  1. Positive means a > b so swap if a - b, do nothing if b - a
  2. Negative means a < b. so do nothing if a - b, swap if b - a
  3. zero means do nothing either it’s a - b or b - a.

Example:

When comparing 60 and 80, the sort() method calls the compare function(60, 80) i.e. sort(compare(60, 80)).The function calculates 60 - 80, and returns -20 (a negative value). The sort function swaps 60 and 80 for a - b case 60 is lower than 80.

Summary:

  • ( a — b )negative means a is smaller than b (a < b)
  • ( a — b )positive means a is greater than b (a > b)
  • (a — b) 0 means a is equal to b (a = b)

--

--

Rajat Gupta
0 Followers

Software Engineer at Volansi | San Jose State University Graduate