Understanding Sort Function in JavaScript.

Understanding Sort Function in JavaScript.

Sort Function

  • Used to Sort Arrays in JavaScript.
  • This method mutates the original array.
  • By default, the order is ascending but we can change the order.
  • We can also provide our compare function to implement custom sorting.

image.png

As you can the result is fine. This is what we needed Array elements got sorted in ascending order and also the array got mutated.

It Gets Tricky.

image.png

What just happened? Why did element 1 get sorted to its correct position but element 2 didn't get sorted.

Why did the sort function not work as expected (Ascending Order)?

For the above code, the expected result is [1,1,2,8,11,22,45], but we get [1,1,11,2,22,45,8].

Reason

The reason is the sort method converts the elements into strings then compares their sequences of UTF-16 code units values.

Explanation

So the 1 is converted to “1”. When we compare two strings like “1” and “22”, the char code is compared means char code of 1 is 49, whereas char code of 2 is 50. Because of 49 < 50, we get = 1, 1, 11 before 2, 22.

This is where compare Function comes to the rescue.

Compare Function

image.png

The compare function takes two arguments. The two arguments are taken as from array on index [0,1] , [1,2] … [arrayLength-2, arrayLength-1] for comparing the pair of elements.

The sorting of elements is based on the return value of compareFunction for each pair of comparisons.

If the function returns a value

  • 0 then the position of a and b is swapped.

  • <=0 then there is no change in position

The function can also be written as

image.png

Complete Sort Function for Numbers

Ascending Order

image.png

Descending Order

image.png

Sort Function for String

There is no need for the compareFunction for sorting strings. We can use the default sort method to sort strings.

image.png

Did you find this article valuable?

Support Vishwajeet Raj by becoming a sponsor. Any amount is appreciated!