How to Sort Numeric Array using JavaScript?


In this article, we are going to learn about the methods of sorting a numerical array in JavaScript. Sorting of an array means to arrange the elements of an array in a particular order i.e. they can be in ascending or the increasing order and they can be arranged in descending or the decreasing order.

There are two ways in which we can sort a numeric array in a particular order in JavaScript −

  • By traversing array with the help of loops

  • By using the sort() method available in JavaScript

Let us discuss both of the above methods in details and sort an array of numerical values.

By traversing array with the help of loops

This is the naive, easiest and the simplest method of sorting an array in a particular order. We can even use this method to sort the numerical array in any language. In this method, we use two different loops and compare each and every element with each other to sort the array. This method will work in the O(N^2) time and O(1) extra space, where N will be the size of the array.

Syntax

Following syntax will show you how you can use the nested loops to sort the array in increasing order −

for(var i=0; i<n; i++){
   for(var j=i+1; j<n; j++){
      // statements inside the loops
   }
}

Let us now understand the practical implementation of this method and sort a array of numerical values with the help of JavaScript code example.

Steps

  • Step 1 − In the first step, we will add an input element to the document of number type and get the number input from the user to push it as an element to the array.

  • Step 2 − In this step, we will add two button elements in the document to perform different tasks. The first button will insert or push the entered value to the array, while the second button will sort the array elements by comparing their numerical values.

  • Step 3 − In the next step we will define a JavaScript function and assign it as a value to the onclick event of the first button added in the previous step to insert the elements in the array.

  • Step 4 − In the fourth step, we will define another JavaScript function which will sort the elements of the array by comparing with each other using the nested loops and assign it as a value to the onclick event of the second button added in the second step.

Example

Below example will explain how to sort a numerical array with the help of two nested loops in ascending order −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort Numeric Array using JavaScript</h2>
   <p>Enter elements of the array in numeric form:</p>
   <input type = "number" id = "inp1" placeholder = "Number Value"><br><br>
   <p id = "prev"> The initial order of the elements stored in the array is:</p>
   <button id = "add" onclick = "setValues()"> Push element to the array</button>
   <button id = "btn" onclick = "sortElement()"> click to sort the array</button>
   <p id = "result"> </p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];
      function setValues() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num = Number(val1);
         myArr.push(num)
         inp1.value = " ";
      }
      function sortElement() {
         var n = myArr.length;
         if (n == 0) {
            result.innerHTML = " <b> The array is empty, Please push the elements in the array and then try to sort. </b> "
         } else {
            prev.innerHTML += " <b> [ " + myArr + " ] </b> ";
            for (var i = 0; i < n; i++) {
               for (var j = i + 1; j < n; j++) {
                  if (myArr[j] < myArr[i]) {
                     // swap the numbers
                     var a = myArr[i];
                     myArr[i] = myArr[j];
                     myArr[j] = a;
                  }
               }
            }
            result.innerHTML = " The array is sorted in the increasing order and the sorted order is: <b> [ " + myArr + " ]. </b> ";
         }
      }
   </script>
</body>
</html>

In this example, we have seen that how we can sort the array of numerical values with the help of two nested loops to traverse and compare each and every element with each other and arrange them in a particular order.

By using the sort() method

The sort() method is a method provided by JavaScript to sort the array elements. It considers all the values of an array as strings and then compare them to sort.

Problem with sort() method

The property of considering the array elements as a string of sort() method limits its use. Because, when there’s an element that contains zeroes in it and is greater than all other elements the sort method will consider that element as smallest sue to string consideration. For example, if an array contains 10 and 7 as elements. So according to math, 10>7 but the sort method will sort in opposite order by considering 10<7 and put 10 before 7 in the sorted order.

Array : [ 7, 5, 10, 12 ];
Order given by sort() method : [ 10, 12, 5, 7 ]
Correct order will be : [ 5, 7, 10, 12 ] 

Solution − The solution to the above problem is to use the comparator function and pass it inside the parenthesis of the sort() method to specify the order in which we want to sort the elements. The comparator function will return three values −

  • Negative− If it returns negative value, that means the first parameter is less that the second parameter, hence tit will come first in the sorted order.

  • Zero− The zero value means both the parameters are same and there will be no change in their positions.

  • Positive− Positive value means the first parameter is larger than the second parameter, hence the second parameter will come first in the sorted order.

Syntax

Following syntax will let you know how to use the sort() method with an array to sort it −

array_name.sort( comparator_function ); 

Let us understand it practically by implementing it inside the JavaScript code example −

Algorithm

The algorithm of the previous example and this example is almost same. You just need to use the sort() method with a comparator function on the array to sort the elements.

Example

Below example will explain the use of the sort() method with comparator function to sort the array elements −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort Numeric Array using JavaScript</h2>
   <p>Enter elements of the array in numeric form:</p>
   <input type = "number" id = "inp1" placeholder = "Number Value"><br><br>
   <p id = "prev">The initial order of the elements stored in the array is:</p>
   <button id = "add" onclick = "setValues()">Push element to the array</button>
   <button id = "btn" onclick = "sortElement()">click to sort the array</button>
   <p id = "result"> </p> 
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];
      function setValues() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num = Number(val1);
         myArr.push(num)
         inp1.value = " ";
      }

      function sortElement() {
         function cmp(a, b) {
            return a - b;
         }
         var n = myArr.length;
         if (n == 0) {
            result.innerHTML = " <b> The array is empty, Please push the elements in the array and then try to sort. </b> "
         }
         else {
            prev.innerHTML += " <b> [ " + myArr + " ] </b> ";
            myArr.sort(cmp);
            result.innerHTML = " The array is sorted in the increasing order and the sorted order is: <b> [ " + myArr + " ]. </b> ";
         }
      }
   </script>
</body>
</html>

In the above example, we have used the sort() method with a comparator function to sort elements of the array in increasing or the ascending order.

NOTE − If you exchange the value we are comparing in the comparator function as well as in the loops method with each other, then the array elements will be sorted in the opposite order such that in the descending or the decreasing order.

Conclusion

In this article, we have learned about the two different methods of sorting the element of a numeric array. We also discussed the problem arises when we use the sort() method to sort the array and the solution to that problem as well with the help of code examples to understand the practical implementation of each of these methods.

Updated on: 20-Nov-2023

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements