Today, we’ve stumbled with a javascript sorting issue. We just wanted to sort some items inside an array but, surprisingly, the results that Google Chrome has shown were completely unexpected.

Let’s say we have a collection of objects with 2 properties: ID (which is a numeric id) and ISACTIVE (boolean here). This collection is properly ordered by ID and you have only one item with ISACTIVE property == true.

Now, we want to sort this collection by ISACTIVE. You may expect that the first element (or the last one; depending wether we want it descending or ascending) may be the one with the ISACTIVE property set to true and the rest of the collection may continue sorted by ID as it originally was.

Well, prepare yourself to face the fact that the expected behaviour is not what you guessed it would be:

All the items with ISACTIVE == false are not really sorted by ID anymore. And if you try to resort again the array using the same exact sort call, you will be able to confirm that the order has changed again!!

What’s going on here? Let’s solve the mistery.

Chrome is using a sorting algorithm which is not stable.
And what does it mean? It means that the algorithm does not guarantee that items with the “same value” (returning 0 in the compare function) will mantain the same relative order.

So, bear in mind that Array.sort algorithm depends on the browser’s implementation and at the time this post is written, all major browsers but Chrome seem to expose an stable implementation of the sorting algorithm. So if you need your sorting to be stable, you will have to create your own sorting algorithm.

You can read this nice article about the subject for more insights on this matter.

Some information about Array.sort function in case you need it.