Misbehaving sort

The default behaviour of Array.prototype.sort() in Javascript may not be what you expect if no compare function is provided.

Quynh Nguyen
2 min readFeb 27, 2021
Photo by Faris Mohammed on Unsplash

I needed to sort an array of integers in Javascript in ascending order recently and reached for Array.prototype.sort().

const array = [0, 2, 1, -2, -1]
array.sort()
//expected result: [-2, -1, 0, 1, 2]

I have used this function many times over and have never encountered any problem. I am aware that you can pass in a compare function as an optional parameter to customise the sorting behaviour, i.e. array.sort([compareFunction]). But for plain old sorting integers ascendingly, the assumption was it was an overkill.

How wrong I was 🤦‍♂! The value of array after being sorted was:

[ -1, -2, 0, 1, 2 ]

Time to reach for the official documentation:

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

So it turns out that without an explicit compare function, Javascript would treat all array elements as strings! The fact that the array only contains data of type number is by the by. It actually makes sense as Javascript is a dynamic language. It does not ask you to declare the data type for the array upon declaration so it would not know your intention. Each item in an array can be of any data type, so Javascript needs to work at the lowest common denominator level.

Once it’s clear, the fix was very simple indeed. Here is how to sort an array of numbers ascendingly in Javascript properly:

const array = [0, 2, 1, -2, -1]
array.sort((a, b) => a - b)
//[-2, -1, 0, 1, 2]

Have you been tripped by this behaviour before?

--

--