Tutorial

Using JavaScript's sort Method for Sorting Arrays of Numbers

Published on September 4, 2020
author

Adebiyi Adedotun

Using JavaScript's sort Method for Sorting Arrays of Numbers

The sort method available on the Array prototype allows you to sort the elements of an array and control how the sorting should be done. The aim of this post is to explain to you why, why not and how the sort method works when sorting an array of numbers.

TL;DR — Sort an array of numbers in ascending order using:
myArray.sort((a, b) => a - b);

Arrays in JavaScript are data structures consisting of a collection of data items. Because Javascript is not a typed language, Javascript arrays can contain different types of elements - strings, numbers, undefined, etc. It’s most often a good idea to have all items in an array be of the same type however.

One of the many operations that can be performed on an array is sorting. Whether you need to know the best students from a collection of grades, the big winners of Wall Street, how much data you’ve been consuming lately, it all involves organizing a collection through sorting.

In the code examples below. We’ll get a collection of eggs in our nest, then sort them both in ascending and descending order. Ready? Let’s do it!

Filling an Array

We declare and initialize a nest array and prefill it with null values - for the moment:

let eggsInNest = new Array(10).fill(null);

We use the static fill method available on the Array constructor method. Next, let’s fill the 10 elements each with random values ranging from 1 - 200:

eggsInNest = eggsInNest.map(() => (Math.floor(Math.random() * 200) + 1));

Sorting

We can then sort simply by calling the sort method on our array without arguments:

eggsInNest.sort();

// e.g.: [109, 136, 156, 188, 19, 190, 2, 34, 55, 90]

As you can see, there’s a slight problem and sorting didn’t quite work out as you might have expected. Read on to learn why and how to fix it.

By default the sort() method sorts the array:

  1. In ascending order
  2. With the items casted to strings

To do this, the sort method calls the String() casting method on every array element and then compares the equivalent strings to determine the correct order.

It would have been that easy, except for the fact that items are compared as strings, which has items sorted as if they were strings of characters instead of numbers. In short, most times, using the sort method without a callback method doesn’t quite work, because sort doesn’t sort the way we expect. Instead, it needs to be explicitly told how to do so - with a callback function.

The callback function or, technically, comparison function receives two arguments (called a and b by convention) and should return 1 if the first argument should preceed the second, -1 if the second argument should preceed the first and 0 if they are equal. Whew! 😓


Let’s create a sortEggsInNest comparison function:

function sortEggsInNest(a, b) {
  if (a > b) {
    return 1;
  } else if (b > a) {
    return -1;
  } else {
    return 0;
  }
}

If you want to be a hotshot 😎, you could reduce the sortEggsInNest comparison function with a ternary operator like so:

function sortEggsInNest(a, b) {
  return a > b ? 1 : b > a ? -1 : 0;
}

Then we can call the sort method again but this time passing in the sortEggsInNest comparison function:

eggsInNest.sort(sortEggsInNest);

And yes, it works… in ascending order.

Descending order

Need to sort in descending order? Just swap the return 1 in the comparison function with return -1 like so:

function sortEggsInNest(a, b) {
  if (a > b) {
    return -1;;
  } else if (b > a) {
    return 1;;
  } else {
    return 0;
  }
}

Or, the short version using ternary operators:

function sortEggsInNest(a, b) {
  return a > b ? -1 : b > a ? 1 : 0;
}

A Shorter Way with Numbers

Finally, there’s even a shorter way to write the comparison function. Here:

eggsInNest.sort((a, b) => a - b);

This is only Ok because the comparison function only returns 1, -1 or 0. and subtracting the two intermediate values yields exactly that. However keep in mind - this can only be used with numeric types or objects whose valueOf() method returns numeric values (such as the Date object).

Further Reading

sort is one of many Array Mutator Methods along with shift, splice, reverse and others. For more info on all methods see How To Use Array Methods in JavaScript: Mutator Methods

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Adebiyi Adedotun

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
4 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I think the last paragraph of the Sort portion of this article should be changed to state that the return value should be positive, negative, or zero, rather than the current 1, -1 and 0. This would match documentation and make it very clear why the later shorthand of a - b works. The Shorter Way with Numbers section would also need a slight edit for this.

This comment has been deleted

    Hi there, I can’t help but get confused by this sentence:

    “The callback function or, technically, comparison function receives two arguments (called a and b by convention) and should return 1 if the first argument should preceed the second, -1 if the second argument should preceed the first and 0 if they are equal. Whew! 😓”

    Shouldn’t it be “should return -1 if the first argument should precede the second”?

    For example, to sort numbers in ascending order, if a < b, a should be in front of b, meaning a should precede b. And in order to do so, we need to return -1. Unless I misunderstood the meaning of precede here.

    Thanks!

    thanks alot, very simple to understand article.

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.