1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Explore ES2019 stable array sorting by example

    Mike SherovMike Sherov
    javascriptJavaScript

    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

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.