JavaScript Sort()
Sorting is very frequently appearing topics in job hunting, mostly during technical interviews. Some languages have built-in sort method to do simple array sorting but in Javascript it’s little complicated. Technically, there is a sort function, however its implementation is not that straight forward.
Get Ashok Maharjan’s stories in your inbox
Join Medium for free to get updates from this writer.
If we take an array with random number and apply sort to it, it does change the order of elements but the sort is not complete. e.g.
This is because sort is a higher order function and takes function as an argument. If we do not provide the function to the sort function, numbers are converted to string and sorted in the unicode order. The function we pass to sort is called a compare function and it follow a certain pattern:
Let’s see how can we translate that to code and use it to sort the above array in an ascending order.
We can simply compare the two elements of the array, if a is lesser that b then we return -1 so that a comes before b. If a is greater than b then we should return 1 so that b comes before a. Provided none of these are true, then we simple return 0, it signifies that both are equal.
The compare function can be easily modified to sort the array in a descending order as well, we simply reverse the conditions and we are done!
We have to be mindful of sort function because it is a mutating function, so if you to preserve your original array you should always use sort by making a copy of the original array first.
That’s all for today and until next time happy coding!






