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 Programming - Beginner Friendly!
🔨 JavaScript Basics
👉 JavaScript Array Filter
👉 JavaScript Array Find
👉 JavaScript forEach (Arrays)
👉 JavaScript Slice (Arrays)
👉 JavaScript Spread Operator
👉 JavaScript Slice(Strings)
👉 JavaScript Includes
👉 JavaScript alert()
👉 Store User Input in a variable with JS
👉 Difference between Let and Const
👉 Sorting Numbers in JS
⚙️ JavaScript Specifics
👉 JavaScript Fetch API
👉 toLocaleDateString in JavaScript

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.


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.

Share via
Copy link
Powered by Social Snap