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;
      }
   }
}

Algorithm 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 5 ? Get the particular columns of two rows and store them in the first and second variables, respectively.

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

Step 7 ? 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 8 ? 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 1: Sorting by Salary (Ascending Order)

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 of 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" border="1" style="width:100%; text-align:center;">
      <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>
   <br>
   <button id="btn"> Sort Table according to salary </button>
   
   <script>
      function sortTableRows() {
         let table = document.getElementById("sort_table");
         var switchContinue = true;

         // continue switching rows until all rows of the table are 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 (column 1 is salary)
               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, switch
               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]);
               switchContinue = true;
            }
         }
      }
      
      let button = document.getElementById('btn');
      button.addEventListener('click', sortTableRows);
   </script>
</body>
</html>

Example 2: Sorting by Name (Descending Order)

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 used the less than 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" border="1" style="width:100%; text-align:center;">
      <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>
   <br>
   <button id="btn"> Sort Table according to Names </button>
   
   <script>
      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;
               
               // get names from first column (index 0)
               let first = allRows[i].getElementsByTagName("TD")[0];
               let second = allRows[i + 1].getElementsByTagName("TD")[0];
               
               // for descending order, check if first < second
               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>

Key Points

  • Use table.rows to access all table rows
  • Use getElementsByTagName("TD")[index] to access specific columns
  • Convert numeric strings with parseInt() for proper number comparison
  • Use toLowerCase() for case-insensitive string sorting
  • The bubble sort algorithm continues until no more swaps are needed

Conclusion

JavaScript table sorting requires a custom bubble sort implementation since built-in array methods don't work directly on table rows. The algorithm compares adjacent rows and swaps them based on column values until the entire table is sorted in the desired order.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements