0

I have this table

   <table name="mytable" id="mytable">
      <tbody>
        <tr>
        <th>Name</th>
        <th>Age</th>
        <th>LastName</th>
        </tr>
        <tr>
        <td>Dean</td>
        <td>18</td>
        <td>Tank</td>
        </tr>
        <tr>
        <td>Jean</td>
        <td>3</td>
        <td>Ted</td>
        </tr>
        <tr>
        <td>Frank</td>
        <td>11</td>
        <td>Marie</td>
        </tr>
        <tr>
        <td>Kid</td>
        <td>8</td>
        <td>Arnold</td>
        </tr>
        <tr>
        <td>Ted</td>
        <td>9</td>
        <td>Marie</td>
        </tr>
        <tr>
        <td>Ma</td>
        <td>10</td>
        <td>Jack</td>
        </tr>
        <tr>
        <td>Martin</td>
        <td>7</td>
        <td>Harvey</td>
        </tr>
        <tr>
        <td>Nelson</td>
        <td>16</td>
        <td>Tom</td>
        </tr>
      </tbody>
    </table>

So I'm trying to display it with the column age sorted in descending order. I have not found any solution to this. The solutions I have found seem to be for alphabetic columns.

The biggest problem is actually having the table displayed with the column Age already sorted in descending order without the user having to tap on a header or button to sort it.

ILOveCoDe
  • 35
  • 6
  • is the data static or created dynamically? – Nidhin Joseph Aug 04 '19 at 23:35
  • If it's a static table, well, it's small, so sort it manually! If the person objects are added dynamically in Javascript, then sort them before adding them to the table markup. – John Aug 05 '19 at 00:15
  • As john already said sort them before adding to table or alternatively add them to table and then run your sorting function – Masoud Keshavarz Aug 05 '19 at 03:53
  • Possible duplicate of [Sorting HTML table with JavaScript](https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript) – Masoud Keshavarz Aug 05 '19 at 03:53

1 Answers1

0

I was able to find a solution using this script

<script>
function sortTable(){
var sorted = $('#myTable tbody tr').sort(function(a, b) {
  var a = $(a).find('td:first-child + td').text(), b = $(b).find('td:first-child + td').text();
  return b.localeCompare(a, false, {numeric: true})
})

$('#myTable').html(sorted);
}
sortTable();
</script>
ILOveCoDe
  • 35
  • 6