Vanilla JavaScript table date sorting

on in JavaScript DOM, JavaScript Time & Date
Last modified on

Vanilla JavaScript Table Date Sorting
Vanilla JavaScript Table Date Sorting

Say we have a table with dates, in the following format:

dd/mm/yyyy

We want to sort this table dynamically based on the date column. Here is the table structure (we’ll keep it simple):

<table id="results" width="360" border="1">
    <thead>
      <tr>
        <th scope="col" width="120">Date Created</th>
        <th scope="col" width="120">Name</th>
        <th scope="col" width="120">Other Data</th>
      </tr>
    </thead>
    <tbody>
       <tr>
        <td>04/04/2015</td>
        <td>Test Name 2</td>
        <td>1</td>
      </tr>
      <tr>
        <td>09/08/2017</td>
        <td>Test Name 5</td>
        <td>2</td>
      </tr>
      <tr>
        <td>07/08/2015</td>
        <td>Test Name 4</td>
        <td>3</td>
      </tr>
      <tr>
        <td>05/04/2015</td>
        <td>Test Name 3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>12/08/2017</td>
        <td>Test Name 6</td>
        <td>5</td>
      </tr>
      <tr>
        <td>21/03/2014</td>
        <td>Test Name 1</td>
        <td>6</td>
      </tr>
    </tbody>
</table>
<button class="sort-season sort-season--start">Season Start</button>

Here is the sorting function, in Vanilla JavaScript:

function convertDate(d) {
    var p = d.split("/");
    return +(p[2] + p[1] + p[0]);
}

function sortByDate(direction) {
    var tbody = document.querySelector("#results tbody");
    // get trs as array for ease of use
    var rows = [].slice.call(tbody.querySelectorAll("tr"));

    if (direction === 'asc') {
        document.querySelector(".sort-season").classList.remove('sort-season--start');
        document.querySelector(".sort-season").classList.add('sort-season--end');

        rows.sort(function (a, b) {
            return (
                convertDate(b.cells[0].innerHTML) -
                convertDate(a.cells[0].innerHTML)
            );
        });
    } else {
        document.querySelector(".sort-season").classList.add('sort-season--start');
        document.querySelector(".sort-season").classList.remove('sort-season--end');

        rows.sort(function (a, b) {
            return (
                convertDate(a.cells[0].innerHTML) -
                convertDate(b.cells[0].innerHTML)
            );
        });
    }

    rows.forEach(function (v) {
        tbody.appendChild(v);
    });
}

document.querySelector(".sort-season").addEventListener("click", () => {
    if (document.querySelector(".sort-season").classList.contains('sort-season--start')) {
        document.querySelector(".sort-season").innerText = "Season End";

        sortByDate('asc');
    } else {
        document.querySelector(".sort-season").innerText = "Season Start";

        sortByDate('desc');
    }
});

And here is the result:

See the Pen Vanilla JavaScript Table Date Sorting by Ciprian (@ciprian) on CodePen.

Related posts