How to Sort HTML Table in JavaScript

Harshit Jindal Feb 02, 2024
How to Sort HTML Table in JavaScript

We often come across situations where we want to make our tables interactive. We may want to sort them just by a click on the column or any other method. HTML doesn’t have any programming capabilities, so we have to use JavaScript to sort an HTML table. Unfortunately, there is no in-built method that helps us to sort the array. Therefore we write our custom method leveraging DOM manipulation capabilities and comparison functions. This tutorial teaches how to sort HTML tables using JavaScript.

Sort HTML Tables Using JavaScript

The User-defined method makes use of the following two helper functions to sort the array.

  • getCellValue()

A function to get the content from a cell given the table row and column index.

We use the children property of the table row to select the ith column using tr.children[i] and then use its innerText or textContent property to get the actual content stored. Once we get the actual content in a cell, we can use a custom comparer to compare and sort these values.

  • comparer()

A function to compare the values of two elements in a given table.

We first get the content of the cells using the getCellValue() function with a specified row and column index. We then check that both are either valid integers or strings and then compare them to find the correct order.

Algorithm

  • Make all the headers in the table clickable by adding an event listener to them.
  • Find all the rows in the selected column except the first row.
  • Use JavaScript’s sort() function with the comparer() to sort the elements.
  • Insert the sorted rows back in the table to get the final sorted table as output.

Code

const getCellValue = (tableRow, columnIndex) =>
    tableRow.children[columnIndex].innerText ||
    tableRow.children[columnIndex].textContent;

const comparer = (idx, asc) => (r1, r2) =>
    ((el1, el2) => el1 !== '' && el2 !== '' && !isNaN(el1) && !isNaN(el2) ?
         el1 - el2 :
         el1.toString().localeCompare(el2))(
        getCellValue(asc ? r1 : r2, idx), getCellValue(asc ? r2 : r1, idx));

// do the work...
document.querySelectorAll('th').forEach(
    th => th.addEventListener(
        'click', (() => {
          const table = th.closest('table');
          Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
              .sort(comparer(
                  Array.from(th.parentNode.children).indexOf(th),
                  this.asc = !this.asc))
              .forEach(tr => table.appendChild(tr));
        })));

All the major browsers support all the methods discussed above.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - JavaScript Table