Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to sort rows in a table using JavaScript ?

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 a 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 the table is sorted
       While (condition = true) {   
      
          // Runs for all rows
          for (i = 1; i < row.length; i++ ) {   
         
             //Check if the 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. 

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
      How to sort rows in a table using JavaScript?
      </title>
   
    <style>
        body {
            text-align: center;
        }
 
        table, th, tr td {
            border: 1px solid black;
        }
        th, td {
            padding: 3px 20px;
        }
        table {
            margin: auto;
        }
    </style>
</head>
 
<body>
    <h1 style="color:green;">
        neveropen
    </h1>
     
    <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>
    <br>
 
    <button onclick="sortTable()">
        Sort
    </button>
 
    <script>
 
        // JavaScript Program to illustrate
        // Table sort on a button click
        function sortTable() {
            let table, i, x, y;
            table = document.getElementById("table");
            let switching = true;
 
            // Run loop until no switching is needed
            while (switching) {
                switching = false;
                let 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>
</body>
 
</html>


Output:

 

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

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to sort rows in a table using JavaScript?
    </title>
    <style>
        body {
            text-align: center;
        }
 
        table,
        th,
        tr td {
            border: 1px solid black;
        }
 
        th,
        td {
            padding: 3px 20px;
        }
 
        table {
            margin: auto;
        }
    </style>
</head>
 
<body>
    <h1 style="color:green">
        neveropen
    </h1>
 
    <h3>
        Click on header to sort in
        ascending and descending
    </h3>
 
    <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) {
            let 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>
</body>
 
</html>


Output:

 

RELATED ARTICLES

Most Popular

Recent Comments