Stable Sort an Array with ES2019 JavaScript

Share this video with your friends

Send Tweet

Before ES2019, array sorting in Javascript was not guaranteed to be stable. In this lesson, we'll learn what stable sorting is by emulating stable sorting in an older version of Node. Then, we'll learn how and when stable sorting matters. Finally, we'll use nvm to switch between an older version of Node and a newer version and compare how each version deals with sorting.

You can find installation instructions for nvm here. Stable sorting was adding to v8 v7.0 (Chrome 70 and Node 11), as noted in this blog post

Laureline Paris
Laureline Paris
~ 5 years ago

More than your well explained lesson here, I highly appreciated that you took time to explain your tool ( here nvm ) for those who didn't yet encounter it šŸ‘

Viktor Soroka
Viktor Soroka
~ 5 years ago

Not a big deal, however, at the end with node 11, there was a wrinkle.

Tony Brown
Tony Brown
~ 5 years ago

I had to run npm audit fix and the lowest version of node that would work was 11.15.0 other than that, things worked as expected. I didn't get the sorting flash from server to client as shown in the video, not an issue, just sayin'. First time using Nuxt.js, I'm really liking this.

J. Matthew
J. Matthew
~ 5 years ago

Nice. As with optional catch binding in the previous video, I didn't know this was an issue, but now that I do, it's good to see that it's fixed!

I'm guessing the stable sorting added to the newer version of Node preceded ES2019 and is just some custom code similar to yours.

Mike Sherov
Mike Sherov(instructor)
~ 5 years ago

I'm guessing the stable sorting added to the newer version of Node preceded ES2019 and is just some custom code similar to yours.

Firefox and Safari had already had stable sorting for a while, although it was never part of the spec. Once v8, the JS engine powering Chrome and Node agreed to implement TimSort (yes, TimSort, not Timesort), which happened to be stable, finally all major implementations had stable sorting so it was added to the spec to gaurantee this property in any future implementation.

JoĆ£o Medrado
JoĆ£o Medrado
~ 5 years ago

What is used as criteria when stable sort is not available and the average in the example is the same?

Mike Sherov
Mike Sherov(instructor)
~ 5 years ago

Hi JoĆ£o,

In practice, this isn't really a question of "what criteria is used" but rather "is the algorithm stable". That is, some sort algorithms can swap equal entries in certain circumstances (usually as a speed boost or way to keep the algorithm simple) while others don't.

ES2020 fixes this by saying that the chosen sort algorithm must be a stable one.