How to sort Numbers in JavaScript

In my latest Reddit Daily Programmer challenge, I came across the task of asking a user for numeric input and then, sort this input in numerical order. To sort numbers in JavaScript, we will use an array and the sort() function.

Sort Numbers in JavaScript using an Array

Alright, let’s dive right in the code.

// Our numbers array
const numbers = [22, 50, 1, 39, 29, 10];

// The sort function
function sortNumbers(array) {
    array.sort((a, b) => a - b);
}

// Calling the function
sortNumbers(numbers)

// Console logging the numbers array, now sorted out.
console.log(numbers)

This is as simple as it gets. JavaScript provides us with the sort() function, so we can utilize that. Let’s break the code down.

  1. We declare our array of numbers.
  2. We create a function that takes our array as an argument and then runs the sort function on the array.
  3. We are calling our sortNumbers(numbers) function with our numbers array as an argument.
  4. We console.log our now sorted numbers array.

The output looks as follows:

How the sort() function works

The probably hardest part to understand in this code is how the actual sort() function works. Let’s break it down then, shall we?

The version I used in my code is simply a shorter version of the original function that was introduced in ES2015.

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

Let us look at the original version, which is maybe a bit easier to understand.

array.sort(function(a, b) {
  return a - b;
});

As you can see, this code is a bit longer. What this function basically does is, it substracts a from b. So for example if you would have two numbers:

sort(1, 5) // It returns -4, meaning a is less than b.

If you want to dig deeper in the ins and outs of this function, there is great Stackoverflow answer to it, you can read it here.

Conclusion

It is fairly straight-forward to sort integer values within an array to a numerical order. You probably will use the sort() function quite a bit so you better get familiar with it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.