Sort Table

HTML

<table class="table table-hover" id="table" style="background-color:#fff;border: 1px solid #cccccc">
  <thead style="background-color:#981e32;">
    <tr>
      <td class="tdsubj" id="id" style="padding:5px;">Id
      </td>
      <td class="tdsubj" id="subject" style="padding:5px;">
        Subject
      </td>
      <td class="tdsubj" id="from" style="padding:5px;">
        From
      </td>
      <td class="tdsubj" id="date" style="padding:5px;">
        Date
      </td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Hello</td>
      <td>Thor</td>
      <td>2020-10-19</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Dinos Suck</td>
      <td>Meteor</td>
      <td>2020-9-5</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Big Ben won't stop ringing</td>
      <td>The Queen</td>
      <td>2020-8-19</td>
    </tr>
  </tbody>
</table>

JavaScript

var table = $("#table");

$("#subject, #from, #id")
  .wrapInner('<span title="sort this column"/>')
  .each(function () {
    var th = $(this),
      thIndex = th.index(),
      inverse = false;

    th.click(function () {
      table
        .find("tbody")
        .find("td")
        .filter(function () {
          return $(this).index() === thIndex;
        })
        .sort(
          function (a, b) {
            return $.text([a]) > $.text([b])
              ? inverse
                ? -1
                : 1
              : inverse
              ? 1
              : -1;
          },
          function () {
            // parentNode is the element we want to move
            return this.parentNode;
          }
        );

      inverse = !inverse;
    });
  });