Jquery sort table data with numbers
I have sorted this table in ascending order but I want it in order of a1,a2,a3,a11.
Can anyone help, please?
function sortTable(table, order) {
var asc = order === 'asc',
tbody = table.find('tbody');
tbody.find('tr').sort(function(a, b) {
if (asc) {
return jQuery('td:first', a).text().localeCompare(jQuery('td:first', b).text());
} else {
return jQuery('td:first', b).text().localeCompare(jQuery('td:first', a).text());
}
}).appendTo(tbody);
}
sortTable($('#mytable'),'asc');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="mytable" id="mytable">
<tbody>
<tr><td>a 11</td></tr>
<tr><td>a 3</td></tr>
<tr><td>a 2</td></tr>
<tr><td>a 1</td></tr>
</tbody>
</table>
You can set options parameter as {numeric: true }
var sorted = $('#mytable tbody tr').sort(function(a, b) {
var a = $(a).find('td:first').text(), b = $(b).find('td:first').text();
return a.localeCompare(b, false, {numeric: true})
})
$('#mytable tbody').html(sorted)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="mytable" id="mytable">
<tbody>
<tr><td>a 11</td></tr>
<tr><td>a 3</td></tr>
<tr><td>a 2</td></tr>
<tr><td>a 1</td></tr>
</tbody>
</table>