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 Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read HTML Tutorial HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript 11 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as 15+ min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac 13 min read Like