How to sort a single table column using JQuery?

Viewed 43

How can I sort a single table column using JQuery? I have a table with a th called duration, with the following values: 45, 15, 30, 90, 60.

I'm trying to sort in ASC order so the end result should be: 15, 30, 45, 60, 90

This is what I have so far, but it's not working at all. Two rows are disappearing from the table and the column or </td>, is still not in ASC order.

custom.js:

function sortTable() {

        var $table = $('#rapports-body tr');
        var $td = $table.children("#duration-td");
        var sortList = Array.prototype.sort.bind($td);

        sortList(function ( a, b ) {

            var aText = a.innerHTML;
            var bText = b.innerHTML;

            if ( aText < bText ) {
                return -1;
            }

            if ( aText > bText ) {
                return 1;
            }

            return 0;
        });

        // Put it right back where we got it
        $table.append($td);

    }
1 Answers

You can simply get content from td of duration column then sort these values and again set new values inside your td tags .

Demo Code :

function sortTable() {
  //get content from duration column
  var $td = $('#rapports-body tbody tr').map(function() {
    return parseInt($(this).find("td:eq(0)").text())
  }).get();
  //sort..them..
  var sortList = $td.sort(function(a, b) {
    return a - b
  });
  //add result inside td ..again
  $('#rapports-body tbody tr').each(function(index) {
    $(this).find("td:eq(0)").text(sortList[index])
  })
}

sortTable()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="rapports-body">
  <thead>
    <th>Duration
    </th>
    <th>Something</th>
  </thead>
  <tbody>
    <tr>
      <td>20</td>
      <td>A3</td>
    </tr>
    <tr>
      <td>34</td>
      <td>A6</td>
    </tr>
    <tr>
      <td>10</td>
      <td>A2</td>
    </tr>
    <tr>
      <td>55</td>
      <td>A1</td>
    </tr>
  </tbody>
</table>

Related