How to sort rows in a table using JavaScript?

28 Jun, 2019
Since JavaScript doesn’t provide any inbuilt functions to sort a table we will be required to use native methods to sort a given table. We will look into the methods in this article.
Approach:A basic algorithm and similar approach will be used for both of the following examples. Loop the program to switch and sort the elements until it is sorted.
// executes on action like button click
Function() {   
   // main loop that runs until table is sorted
   While (condition = true) {   
      // runs for all rows
      for (i = 1; i < row.length; i++ ) {   
         // check if switch is required
         if (element_A > element_B){   
            // perform switch
            PerformSwitch();   
         }
      }
   }
}

Example 1: This example sorts the table using a while loop to switch the rows until the rows are sorted.
<!DOCTYPE html><html>  <head>    <title>GeeksforGeeks</title>    <style>        table {            border-spacing: 0;            width: 80%;            border: 1px solid #dddd;        }                  th,        td {            text-align: left;            padding: 15px;        }                  tr:nth-child(even) {            background-color: #008000        }    </style></head>  <body>      <center>        <h1 style="color:green">GeeksforGeeks</h1>        <p>            <button onclick="sortTable()">Sort</button>        </p>          <table id="table">            <tr>                <th>Country</th>                <th>Capital</th>            </tr>            <tr>                <td>United states of America</td>                <td>Washington DC</td>            </tr>            <tr>                <td>India</td>                <td>New Delhi</td>            </tr>            <tr>                <td>Australia</td>                <td>Canberra</td>            </tr>            <tr>                <td>Germany</td>                <td>Berlin</td>            </tr>          </table>          <script>            // JavaScript Program to illustrate            // Table sort on a button click            function sortTable() {                var table, i, x, y;                table = document.getElementById("table");                var switching = true;                  // Run loop until no switching is needed                while (switching) {                    switching = false;                    var rows = table.rows;                      // Loop to go through all rows                    for (i = 1; i < (rows.length - 1); i++) {                        var Switch = false;                          // Fetch 2 elements that need to be compared                        x = rows[i].getElementsByTagName("TD")[0];                        y = rows[i + 1].getElementsByTagName("TD")[0];                          // Check if 2 rows need to be switched                        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())                            {                              // If yes, mark Switch as needed and break loop                            Switch = true;                            break;                        }                    }                    if (Switch) {                        // Function to switch rows and mark switch as completed                        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);                        switching = true;                    }                }            }        </script>    </center></body>  </html>
Output before click:
Output after click:
Example 2: This example sorts the table using the same loop technique but executes the function for both the given columns, as well as in both directions (ascending and descending).
<!DOCTYPE html><html>  <head>    <title>GeeksforGeeks</title>    <style>        table {            border-spacing: 0;            width: 80%;            border: 1px solid #dddd;        }                  th,        td {            text-align: left;            padding: 15px;        }                  tr:nth-child(even) {            background-color: #008000        }    </style></head>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>          <p><strong>          Click the headers to sort in           ascending and descending.          </strong></p>          <table id="table">            <tr>                <!--Calls sortTable function(0 for                    country and 1 for capital) when                     headers are clicked-->                <th onclick="sortTable(0)">Country</th>                <th onclick="sortTable(1)">Capital</th>            </tr>            <tr>                <td>United states of America</td>                <td>Washington DC</td>            </tr>            <tr>                <td>India</td>                <td>New Delhi</td>            </tr>            <tr>                <td>Australia</td>                <td>Canberra</td>            </tr>            <tr>                <td>Germany</td>                <td>Berlin</td>            </tr>        </table>          <script>            // JavaScript program to illustrate            // Table sort for both columns and both directions.            function sortTable(n) {                var table;                table = document.getElementById("table");                var rows, i, x, y, count = 0;                var switching = true;                  // Order is set as ascending                var direction = "ascending";                  // Run loop until no switching is needed                while (switching) {                    switching = false;                    var rows = table.rows;                      //Loop to go through all rows                    for (i = 1; i < (rows.length - 1); i++) {                        var Switch = false;                          // Fetch 2 elements that need to be compared                        x = rows[i].getElementsByTagName("TD")[n];                        y = rows[i + 1].getElementsByTagName("TD")[n];                          // Check the direction of order                        if (direction == "ascending") {                              // Check if 2 rows need to be switched                            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())                                {                                // If yes, mark Switch as needed and break loop                                Switch = true;                                break;                            }                        } else if (direction == "descending") {                              // Check direction                            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase())                                {                                // If yes, mark Switch as needed and break loop                                Switch = true;                                break;                            }                        }                    }                    if (Switch) {                        // Function to switch rows and mark switch as completed                        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);                        switching = true;                          // Increase count for each switch                        count++;                    } else {                        // Run while loop again for descending order                        if (count == 0 && direction == "ascending") {                            direction = "descending";                            switching = true;                        }                    }                }            }        </script>    </center></body>  </html>
Output before sort
Output for 1st column sort(ascending):
Output for 2nd column sort(descending):
JavaScript-Misc
Picked
HTML
JavaScript
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request