How to sort rows in a table using JavaScript?


We can’t use the built-in sort() method of JavaScript to sort the table rows based on the particular column. So, we need to create a custom algorithm to sort table rows. In this tutorial, we will learn to sort tables and rows using JavaScript.

Here, we will look at different examples to sort table rows in ascending and descending order.

Syntax

Users can follow the syntax below to sort rows in a table using JavaScript.

var switchContinue = true;
while (switchContinue) {
   switchContinue = false;
   var allRows = table.rows;
   for ( Iterate through all rows ) {
      if (first.innerHTML > second.innerHTML) {
         allRows[i].parentNode.insertBefore(allRows[i + 1], allRows[i]);
         switchContinue = true;
         break;
      }
   }
} 

Steps

Follow the below steps to sort rows in a table using JavaScript −

Step 1 − Create a switchContinue variable and initialize with true value, which keeps track of whether the further switch is required for the table rows.

Step 2 − Use the while loop, and make iterations until the value of the switchContinue variable is true.

Step 3 − In the while loop, assign false to the switchContinue variable by assuming that no further switches are required.

Step 4 − Get all rows of the table using the rows property.

Step 4.1 − Get the particular columns of two rows and store them in the first and second variables, respectively.

Step 5 − Get the innerHTML of columns and compare them. If switching requires based on the comparison results of two values, switch both rows.

Step 6 − Assign a true value to the switchContinue variable. As we have switched two rows, we need to check if any other rows require switching. After that, break the for loop using the break keyword.

Step 7 − If the value of the switchContinue variable remains false while every iteration of for loop, the array is sorted, and no further iteration of the while loop is required.

Example

In the example below, we have created the table with two columns named name and salary. Also, we have added five rows with different column values in the table.

In the JavaScript part, we implement the above algorithm to sort table rows based on the ascending order or salary values. Users can see how we have accessed the second column of two rows and used the parseInt() method to convert salary values into the number. After that, we compared the salary values and changed the order of rows in the table.

<html>
<body>
   <h2>Sorting the <i>table rows in ascending order</i> in JavaScript.</h2>
   <table id = "sort_table">
      <tr>
         <th> Name </th>
         <th> Salary </th>
      </tr>
      <tr>
         <td> Person 1 </td>
         <td> 40000 </td>
      </tr>
      <tr>
         <td> Person 2 </td>
         <td> 30000 </td>
      </tr>
      <tr>
         <td> Person 3 </td>
         <td> 20000 </td>
      </tr>
      <tr>
         <td> Person 4 </td>
         <td> 50000 </td>
      </tr>
      <tr>
         <td> Person 5 </td>
         <td> 10000 </td>
      </tr>
   </table>
   <button id = "btn"> Sort Table according to salary </button>
   <script>
      let output = document.getElementById('output');
      function sortTableRows() {
         let table = document.getElementById("sort_table");
         var switchContinue = true;

         // continue switching rows until all rows of the table are not sorted
         while (switchContinue) {
            switchContinue = false;
            var allRows = table.rows;
            let i;

            // iterate through all rows and check if the switch requires
            for (i = 1; i < (allRows.length - 1); i++)
            {
               var switchRow = false;

               // get two rows of the table
               let first = allRows[i].getElementsByTagName("TD")[1];
               let second = allRows[i + 1].getElementsByTagName("TD")[1];

               // if the salary in the first row is greater than the second row, we require to switch row
               if (parseInt(first.innerHTML) > parseInt(second.innerHTML)) {
                  switchRow = true;
                  break;
               }
            }

            // switch the row, if required
            if (switchRow) {
               allRows[i].parentNode.insertBefore(allRows[i + 1], allRows[i]);

               // check further if any switch requires
               switchContinue = true;
            }
         }
      }
      let button = document.getElementById('btn');
      button.addEventListener('click', () => { sortTableRows() }) 
   </script>
</body>
</html>

Example

In the example below, the table contains the name and ages of users. We have sorted all table rows based on the user’s names in descending order. We have used the toLowerCase() method to convert name values into lowercase and compared them.

As we require sorting the table rows in descending order, we have taken less than the operator to compare the column values of both rows.

<html>
<body>
   <h2>Sorting the <i>table rows in descending order</i> in JavaScript</h2>
   <table id = "sort_table">
      <tr>
         <th> Name </th>
         <th> Age </th>
      </tr>
      <tr>
         <td> John </td>
         <td> 23 </td>
      </tr>
      <tr>
         <td> Akshay </td>
         <td> 30 </td>
      </tr>
      <tr>
         <td> Alice </td>
         <td> 32 </td>
      </tr>
      <tr>
         <td> Bob </td>
         <td> 12 </td>
      </tr>
      <tr>
         <td> Shubham </td>
         <td> 22 </td>
      </tr>
   </table>
   <button id = "btn"> Sort Table according to Names </button>
   <script>
      let output = document.getElementById('output');
      function sortTableRows() {
         let table = document.getElementById("sort_table");
         var switchContinue = true; 
         while (switchContinue) {
            switchContinue = false;
            var allRows = table.rows;
            let i;
            for (i = 1; i < (allRows.length - 1); i++) {
               var switchRow = false;
               let first = allRows[i].getElementsByTagName("TD")[0];
               let second = allRows[i + 1].getElementsByTagName("TD")[0];
               if (first.innerHTML.toLowerCase() <second.innerHTML.toLowerCase()) {
                  switchRow = true;
                  break;
               }
            }
            if (switchRow) {
               allRows[i].parentNode.insertBefore(allRows[i + 1], allRows[i]);
               switchContinue = true;
            }
         }
      }
      let button = document.getElementById('btn');
      button.addEventListener('click', () => { sortTableRows() })
   </script>
</body>
</html>

Users learned to sort the table based on particular column values. In the first example, we learned to sort rows in ascending order, and in the second example, we learned to sort rows in descending order.

Furthermore, we can also sort the table rows based on multiple table columns. We need to change the if statement's condition to sort rows based on multiple column values.

Updated on: 22-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements