Chad Chad - 4 months ago 7
jQuery Question

jQuery sort HTML tables with custom order

I want to be able to sort my tables by month.

Example:

February
December
October
August
July


When sorted it should be

February
July
August
October
December


I've experimented with a few jQuery plugins online and none of them had the option to create a custom sort order.

Thanks!

Answer

Let's immagine to add an attribute for each table row called sort-order.

Now, we can order the table according to this attribute:

$(function () {
  // sort the table rows
  var sortedTableRows = $('table tbody tr').get().sort(function (a, b) {
    var aVal = +a.getAttribute('sort-order');
    var bVal = +b.getAttribute('sort-order');
    return (aVal > bVal) ? 1 : (aVal < bVal) ? -1 : 0;
  });
  
  // substitute the table rows with the ordered one
  $.each(sortedTableRows, function (i, e) {
    $('table tbody').append(e);
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<table>
    <thead>
    <th>
        <tr>
            <td>Months</td>
        </tr>
    </th>
    </thead>
    <tbody>
    <tr sort-order="12">
        <td>January</td>
    </tr>
    <tr sort-order="11">
        <td>February</td>
    </tr>
    <tr sort-order="10">
        <td>March</td>
    </tr>
    <tr sort-order="9">
        <td>April</td>
    </tr>
    <tr sort-order="8">
        <td>May</td>
    </tr>
    <tr sort-order="7">
        <td>June</td>
    </tr>
    <tr sort-order="6">
        <td>July</td>
    </tr>
    <tr sort-order="5">
        <td>August</td>
    </tr>
    <tr sort-order="4">
        <td>September</td>
    </tr>
    <tr sort-order="3">
        <td>October</td>
    </tr>
    <tr sort-order="2">
        <td>November</td>
    </tr>
    <tr sort-order="1">
        <td>December</td>
    </tr>
    </tbody>
</table>