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.

4
  • is the data static or created dynamically? Commented Aug 4, 2019 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. Commented Aug 5, 2019 at 0:15
  • As john already said sort them before adding to table or alternatively add them to table and then run your sorting function Commented Aug 5, 2019 at 3:53
  • Possible duplicate of Sorting HTML table with JavaScript Commented Aug 5, 2019 at 3:53

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.