JavaScript Sort Table on Header Click

JavaScript Sort Table on Header Click
Code Snippet:Pure JavaScript Sortable Table
Author: Murat Doğan
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 6,293
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to sort the HTML table on header click. It stores the table data in const objects and renders that to the HTML table dynamically. In order to sort the table columns, it uses the JavaScript array sort method.

How to Create JavaScript Sort Table on Header Click

1. First of all, create the HTML table element with a unique id and place “th” element with the data-filter-value attribute. Similarly, define data-filter values as follows:

 <table id="squadTable" class="table table-dark table-striped">
    <thead>
        <tr>
            <th data-filter-value="no" class="active">No <i class="fa fa-sort"></i></th>
            <th>Adı</th>
            <th>Pozisyonu</th>
            <th data-filter-value="dateOfBirth">Yaş <i class="fa fa-sort"></i></th>
            <th data-filter-value="match">Maç <i class="fa fa-sort"></i></th>
            <th data-filter-value="goal">Gol <i class="fa fa-sort"></i></th>
            <th data-filter-value="assist">AST <i class="fa fa-sort"></i></th>
            <th data-filter-value="yellowCard">SK <i class="fa fa-sort"></i></th>
            <th data-filter-value="doubleYellowCard">ÇSK <i class="fa fa-sort"></i></th>
            <th data-filter-value="redCard">KK <i class="fa fa-sort"></i></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

2. After that, define the following CSS style for the table header “th” element:

th[data-filter-value] {
  cursor: pointer;
}
th.active {
  color: red;
}

3. Now, add the following JS table sort code to your project. In this code, place the table data inside the JavaScript array of objects.

const data = [{
  "id": "1233213",
  "no": 17,
  "fullName": "Murat DoÄŸan",
  "position": "CMD",
  "age": 29,
  "dateOfBirth": "1985-08-06T00:00:00",
  "match": 12,
  "time": 1080,
  "goal": 12,
  "assist": 4,
  "yellowCard": 3,
  "doubleYellowCard": 0,
  "redCard": 2 },
{
  "id": "41233213",
  "no": 58,
  "fullName": "Lorem Ipsum",
  "position": "GK",
  "age": 28, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 34,
  "time": 3400,
  "goal": 1,
  "assist": 17,
  "yellowCard": 8,
  "doubleYellowCard": 3,
  "redCard": 5 },
{
  "id": "51233213",
  "no": 18,
  "fullName": "Dolor Sit",
  "position": "ST",
  "age": 33, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 5,
  "time": 120,
  "goal": 1,
  "assist": 2,
  "yellowCard": 5,
  "doubleYellowCard": 1,
  "redCard": 4 },
{
  "id": "61233213",
  "no": 27,
  "fullName": "Amet Dolor",
  "position": "DL",
  "age": 18, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 2,
  "time": 12,
  "goal": 0,
  "assist": 1,
  "yellowCard": 3,
  "doubleYellowCard": 4,
  "redCard": 5 }];


let currentFilter = "",
prevFilter = "",
orderAsc = true;

const toggleOrder = () => {
  if (currentFilter === prevFilter) {
    orderAsc = !orderAsc;
  } else {
    orderAsc = true;
  }
};

const calcAge = birthDate => {
  let bDate = new Date(birthDate),
  bDateYear = bDate.getUTCFullYear(),
  now = new Date().getFullYear();

  return now - bDateYear;
};

const sortTable = (array, sortKey) => {
  return array.sort((a, b) => {
    let x = a[sortKey],
    y = b[sortKey];

    return orderAsc ? x - y : y - x;
  });
};

const renderTable = tableData => {
  return `${tableData.map(item => {
    if (item.dateOfBirth.length > 2) {
      item.dateOfBirth = calcAge(item.dateOfBirth);
    }
    return (
      `<tr>
                        <td>${item.no}</td>
                        <td>${item.fullName}</td>
                        <td>${item.position}</td>
                        <td>${item.dateOfBirth}</td>
                        <td>${item.match}</td>
                        <td>${item.goal}</td>
                        <td>${item.assist}</td>
                        <td>${item.yellowCard}</td>
                        <td>${item.doubleYellowCard}</td>
                        <td>${item.redCard}</td>
                    </tr>`);

  }).join('')}`;
};

const appendTable = (table, destination) => {
  document.querySelector(destination).innerHTML = table;
};

const handleSortClick = () => {
  const filters = document.querySelectorAll('#squadTable th');

  Array.prototype.forEach.call(filters, filter => {
    filter.addEventListener("click", () => {
      if (!filter.dataset.filterValue) return false;

      Array.prototype.forEach.call(filters, filter => {
        filter.classList.remove('active');
      });
      filter.classList.add('active');
      currentFilter = filter.dataset.filterValue;
      toggleOrder();
      init();
    });
  });
};

const init = () => {
  let newTableData = sortTable(data, currentFilter),
  tableOutput = renderTable(newTableData);

  appendTable(tableOutput, '#squadTable tbody');

  prevFilter = currentFilter;
};

init();
handleSortClick();

That’s all! hopefully, you have successfully integrated this JavaScript sort table code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X