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, sorting this input in numerical order. To sort numbers in JavaScript, we will use an array and the sort() function.

🔥 Learn JavaScript - Beginner Friendly!

👉 JavaScript Array Filter – Made Easy
👉 JavaScript Array Find – Made Easy
👉 Difference between Let and Const
👉 Sorting Numbers in JS!
👉 Store User Input in a variable with JS!
👉 JavaScript Spread Operator – Made Easy
👉 JavaScript Slice (Arrays) – Made Easy
👉 JavaScript Slice(Strings) – Made Easy
👉 JavaScript Includes – Made Easy
👉 JavaScript forEach (Arrays) - Made Easy
👉 toLocaleDateString in JavaScript - For Humans
👉 JavaScript Fetch API - Made Easy

Table of Contents

Sort Numbers in JavaScript using an Array

Alright, let's dive right into 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)
Code language: JavaScript (javascript)

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)
Code language: JavaScript (javascript)

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

array.sort(function(a, b) { return a - b; });
Code language: PHP (php)

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

sort(1, 5) // It returns -4, meaning a is less than b.
Code language: JavaScript (javascript)

If you want to dig deeper into the ins and outs of this function, there is a 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.