JavaScript - How to Sort Rows in a Table? Last Updated : 26 Nov, 2024 Comments Improve Suggest changes Like Article Like Report Rows in a table are horizontal sections that hold data, organizing information across columns in a structured, easy-to-read format. To sort table rows in JavaScript, create a function that compares rows based on cell values. Use a loop to check and swap rows as needed until all rows are in order.Approach to Sort Rows an a Table When the "Sort" button is clicked, the JavaScript sortTable() function starts, organizing the rows alphabetically based on the country names.The function compares each row's country name and swaps rows if needed, repeating until the table is fully sorted alphabetically.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> <style> body { text-align: center; } table, th, tr td { border: 1px solid black; } th, td { padding: 3px 20px; } table { margin: auto; } </style> </head> <body> <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> OutputExample 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> <style> body { text-align: center; } table, th, tr td { border: 1px solid black; } th, td { padding: 3px 20px; } table { margin: auto; } </style> </head> <body> <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 Comment More infoAdvertise with us Next Article JavaScript - How to Sort Rows in a Table? V vishodushaozae Follow Improve Article Tags : HTML JavaScript-Questions Similar Reads How to Sort a list in Scala? Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S 2 min read JavaScript - Sort a Numeric Array Here are some common methods to Sort Numeric Array using JavaScript. Please note that the sort function by default considers number arrays same as an array of stings and sort by considering digits as characters.Using sort() with a Comparison Function - Most UsedThe sort() method in JavaScript, when 2 min read How to Sort an Array in Scala? Sorting arrays effectively is essential for many applications, regardless of whether you're working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situati 5 min read How to Sort a Pivot Table in Excel : A Complete Guide Sorting a Pivot Table in Excel is a powerful way to organize and analyze data effectively. Whether you want to sort alphabetically, numerically, or apply a custom sort in Excel, mastering this feature allows you to extract meaningful insights quickly. This guide walks you through various Pivot Table 7 min read How to Use Sortby in Scala? In this article, we will learn to use the sortBy function in Scala. The sortBy function is used to sort elements in a collection based on specified sorting criteria. Table of Content Using SortBy for Sorting an ArrayUsing SortBy for Sorting an Array in Reverse Order Using SortBy for Sorting By the S 4 min read How to Sort Data in Excel: Easy Step by Step Process Sorting data in Excel is a simple yet powerful way to organize your information, making it easier to analyze and interpret. Whether you're working with a small dataset or a large table, knowing how to sort data in Excel can help you find the information you need quickly. In this guide, we will cover 5 min read Java Program to Sort an ArrayList ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unorder 6 min read Angular PrimeNG Table Sort Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use Table Sort in Angular PrimeNG. Angular PrimeNG Table Sort en 5 min read Angular PrimeNG Table Sorting Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Table Sorting in Angular PrimeNG. Angular PrimeNG Table Sorting 5 min read How to sort an Array in C# | Array.Sort() Method Set â 2 Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method 9 min read Like