Explore ES2019 stable array sorting by example

Mike Sherov
InstructorMike Sherov

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Before ES2019, array sorting in Javascript was not guaranteed to be stable. In this lesson, we'll learn what stable sorting is by seeing an example of unstable sorting. We'll use nvm to switch between an older version of Node and a newer version and compare how each version deals with sorting. Lastly, we'll mimic stable sorting by adding indexes to our array elements and comparing the indexes during sort.

You can find installation instructions for nvm here: https://github.com/creationix/nvm Stable sorting was adding to v8 v7.0 (Chrome 70 and Node 11), as noted here: https://v8.dev/blog/array-sort

Instructor: [00:00] Here we have an array of scores. Each score is an object with the name of the student and the score they achieved on our test. Here's a sorting function that will order the students by their score, ignoring their name.

[00:14] Because everyone scored the same on the test, if we logged their scores, we'll see that the order hasn't changed. This is because sorting, as of ES2019, is now stable.

[00:26] Stable sorting means that two elements in an array with the same sort value will appear in the same order in the output array as they were in the input array. That is, if Alice comes before Bobby in the input array, Alice will come before Bobby in the output array.

[00:44] This wasn't always the case in JavaScript. Let's install an older version of Node to see how this has changed. I'll do this by using NVM. NVM is a Node Version Manager which lets you seamlessly switch between versions of Node.

[00:58] You can see that I'm now using Node 10. If I run the same script again, you can see that it now puts Fermi at top even though Fermi comes after Alice in the input array.

[01:11] If you want it to mimic stable sorting prior to ES2019, we can do so by first adding an index to every element in the array, and then considering the index in the case of breaking a tie.

[01:30] We do this by first checking to see if a.score equals b.score, and if so, returning a.index - b.index, otherwise, falling back to returning a difference of the scores.

[01:45] If we run this again, we now see that it's correctly sorted. Thankfully, ES2019 takes away this headache for us. Simply by using the latest version of Node, you once again have stable sorting.