JavaScript sort numbers ascending | Simple example code

Use Array sort() Method to sort numbers in ascending order in JavaScript. But the sort() method sorts the array of elements alphabetically, So, you need to sort an array of integers correctly by utilizing a compare function.

Example code JavaScript sort numbers ascending

HTML example code of Sorting the numbers array numerically in ascending order using the sort method and a compare function.

<!DOCTYPE html>
<html>
<head>
    <script>
        var numbers = [0, 5, 1, 3, 7, 2, 9];

        numbers.sort(); 
        alert(numbers); 

        numbers.sort(function(a, b){
            return a - b;
        });
        alert(numbers); 
    </script><script>
    </script>

</head>
<body>

</body>
</html>

Output:

JavaScript sort numbers ascending

How to JavaScript array of numbers without sort function?

Here is a Bubble sort function for you to reference, but as mentioned there are many different sorting algorithms.

<!DOCTYPE html>
<html>
<head>
    <script>
        function bubbleSort(array) {
          var done = false;
          while (!done) {
            done = true;
            for (var i = 1; i < array.length; i += 1) {
              if (array[i - 1] > array[i]) {
                done = false;
                var tmp = array[i - 1];
                array[i - 1] = array[i];
                array[i] = tmp;
            }
        }
    }

    return array;
}

var numbers = [12, 10, 15, 11, 14, 13, 16];
bubbleSort(numbers);
console.log(numbers);
</script><script>
</script>

</head>
<body>

</body>
</html>

Output:

Array(7) [ 10, 11, 12, 13, 14, 15, 16 ]

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

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