How to sort an array on multiple columns using JavaScript?


A array with multiple columns is an array that contains multiple elements at single index or position OR we can say that it is an array of arrays that contains multiple arrays at each index of it and we have to sort that array according to the elements of those contained arrays.

In this article, we are going to learn about the method of sorting an array of arrays with the help of sort() method. We will use the comparator function to compare the elements of inner arrays with each other and sort them accordingly.

Let us see how we can create an array of arrays with user inputs and then sort the array.

Syntax

Following syntax will show you how you can create an array of arrays using JavaScript −

var first_array = [];
var second_array = [
	userInput1,
	userInput2
];
first_array.push(second_array);

In the above syntax, we created two different arrays named first_array and second_array. In the second_array, we put the values entered by the user and then push the second_array into the first_array with the help of push() method.

Let us now discuss how we can use the sort() method to sort the array elements according to the numeric values of the contained arrays.

Steps

  • Step 1 − In the first step, we will add two different input elements in the HTML document of text and number type to get the inputs from the user and then push them to the original array which we will sort later.

  • Step 2 − In the next step, we will add two different buttons with onclick events associated with them, where the first button will push the entered values in the subarray which will be later pushed into the original array and the second button will sort the original array and display the result on the user screen.

  • Step 3 − In this step, we will define a JavaScript function which will add the entered inputs to the subarray as well as push that subarray into the original array and assign this function as a value to the onclick event of the first button defined in the last step..

  • Step 4 − In the fourth step, we will define another JavaScript function which will use the comparator function to sort the elements of the array according to the numeric values of the subarrays and display the result on the user screen.

  • Step 5 − In the last step, we will assign the function declared in the previous step as a value to the onclick event to the of the second button defined in the third step.

Example

The below example will explain how you can use the sort() method to sort the array of array according to numeric values stored in them −

<!DOCTYPE html>
<html lang = "en">
<body>
   <h2>Sort an array on multiple columns using JavaScript</h2>
   <p>Enter your Name and Age to insert into array:</p>
   <input type = "text" id = "inp1" placeholder = "Name"> <br><br>
   <input type = "number" id = "inp2" placeholder = "Age"> <br><br>
   <button id = "add" onclick = "insertArr()"> Add Item to array</button>
   <button id = "btn" onclick = "sortArr()"> click to sort </button>
   <p id = "prev">The initial order of values in array of arrays is:</p>
   <p id = "result">The final sorted order of values in array of arrays is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];

      function insertArr() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var name = val1;
         var inp2 = document.getElementById("inp2");
         var val2 = inp2.value;
         var age = Number(val2);
         var arr = [
            name,
            age
         ]
         myArr.push(arr);
         inp1.value = " ";
         inp2.value = " ";
      }

      function sortArr() {

         for (var item of myArr) {
            prev.innerHTML += " <b> [ " + item + " ] </b> ";
         }

         function cmp(a, b) {
            var xa = a[1];
            var xb = b[1];

            if (xa < xb)
               return -1;
            if (xa > xb)
               return 1;
            return 0;
         }

         myArr.sort(cmp);
         for (var item of myArr) {
            result.innerHTML += " <b> [ " + item + " ] </b> ";
         }
      }
   </script>
</body>
</html>

In the above example, we have sorted the array of arrays according the numerical values stored in the subarrays contained by the original array.

Let us see one more code example in which we will sort the array according to the length of the string elements contained by the subarrays of the original array.

Algorithm

The algorithm of this example is similar to the algorithm of the previous example. You can sort the array according to the length of the string values contained by the subarrays of the original array just by performing some changes in the comparator function cmp in the last example. The change you have to perform is explained below −

  • Change the values of variables xa and xb from a[1] and b[1] to a[0].length and b[0].length and by performing these changes you are good to go for sorting the array according to the length of string values.

Example

Below example will help you understand the change you have to perform in previous algorithm practically and it also sort the array according to the string values contained by subarrays of the original array −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort an array on multiple columns using JavaScript</h2>
   <p>Enter your Name and Age to insert into array:</p>
   <input type="text" id="inp1" placeholder="Name"><br><br>
   <input type="number" id="inp2" placeholder="Age"><br><br>
   <button id="add" onclick="insertArr()"> Add Item to array</button>
   <button id="btn" onclick="sortArr()"> click to sort </button>
   <p id="prev">The initial order of values in array of arrays is:</p>
   <p id="result">The final sorted order of values in array of arrays is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];
      function insertArr() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var name = val1;
         var inp2 = document.getElementById("inp2");
         var val2 = inp2.value;
         var age = Number(val2);
         var arr = [
            name,
            age
         ]
         myArr.push(arr);
         inp1.value = "";
         inp2.value = " ";
      }

      function sortArr() {

         for (var item of myArr) {
            prev.innerHTML += " <b> [ " + item + " ] </b> ";
         }

         function cmp(a, b) {
            var xa = a[0].length;
            var xb = b[0].length;

            if (xa < xb)
               return -1;
            if (xa > xb)
               return 1;
            return 0;
         }

         myArr.sort(cmp);
         for (var item of myArr) {
            result.innerHTML += " <b> [ " + item + " ] </b> ";
         }
      }
   </script>
</body>
</html> 

In the above example, we have used the sort() method with the comparator function in such a way that it sort the original array according to the length of the string values contained by the subarrays.

Conclusion

In this article, we have discussed about the sorting of an array of arrays with different types of values. We have understood it practically with the help of code example, where, we use the subarrays with string and the numeric values and sort them according to the numeric and the length of string values respectively in the code examples discussed above, in the article.

Updated on: 20-Nov-2023

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements