New Stable Sort Array in Javascript: ES10/2019

JavaScript , , 2 Comments

In this article, we will learn the new functionality of sort array in JavaScript with examples and talk about its stability.

Stable sort array in JavaScript means that if two elements in the array have the same sorting value will appear in the original order that we had before sorting. Before ES10/2019 Update , Let’s say we have an array of dogs with ratings and name note that the array is pre-sorted alphabetically by name.

This Example isn’t weird 😛

const dogs = [
  { name: 'Abby',   rating: 12 },
  { name: 'Bandit', rating: 13 },
  { name: 'Choco',  rating: 14 },
  { name: 'Daisy',  rating: 12 },
  { name: 'Elmo',   rating: 12 },
  { name: 'Falco',  rating: 13 },
  { name: 'Ghost',  rating: 14 },
];
dogs.sort((a, b) => b.rating - a.rating);

In the above example, the array is pre-sorted by name and we sorted it with its rating to get the highest rated first. The results you got before the ES10 update.

[
  { name: 'Ghost',  rating: 14 }, // 😢
  { name: 'Choco',  rating: 14 }, // 😢
  { name: 'Bandit', rating: 13 },
  { name: 'Falco',  rating: 13 },
  { name: 'Abby',   rating: 12 },
  { name: 'Daisy',  rating: 12 },
  { name: 'Elmo',   rating: 12 },
]

The problem is Ghost and Choco have the same rating of 14 and they were pre-sorted alphabetically by their name but when you applied the sort method, it messed with its name sorting. The stability of the sort method is none. That’s what the new update about, Now if you do sort on the above array, it doesn’t mess with its stability. For example below:

[
  { name: 'Choco',  rating: 14 },
  { name: 'Ghost',  rating: 14 },
  { name: 'Bandit', rating: 13 },
  { name: 'Falco',  rating: 13 },
  { name: 'Abby',   rating: 12 },
  { name: 'Daisy',  rating: 12 },
  { name: 'Elmo',   rating: 12 },
]

Did you noticed in the example above Choco comes first, It doesn’t mess with its stability. The name sorting remains as it is because that’s the order we had before sorting.

Note: Although stability is now required per spec, JavaScript engines are still free to implement whatever sorting algorithm they prefer. V8 uses Timsort, for example. The spec does not mandate any particular sorting algorithm.

Browser Support

Support data as per chrome v8 blog

Property
Stable Array sort70?Yesyes?

Thank you for reading 🙂 Please share it with love.

Spread the love
  • 46
    Shares

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Rajnish RajputSkyulaga Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Skyulaga
Guest

Thanks for doing this post.it really helps to sort orderly ,when more than one column and also having same values in the column.
it reminds me of row number and partition in SQL server.