How to sort rows in a table using JavaScript?

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output before click:
Unsorted table

Output after click:
Sorted table

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).

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output before sort
Unsorted table 2

Output for 1st column sort(ascending):
Sorted table 2

Output for 2nd column sort(descending):
sorted table 2 desc



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.