2

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>
vaishali kapadia
  • 934
  • 11
  • 22
  • Remember that the `.sort()` function sorts lexicographically, meaning that `11` will always come after `1` but before `2`, for example. If you want to look for **natural sort**, you can try third-party plugins, such as: [natsort](https://github.com/bubkoo/natsort). There are also other solutions already available on StackOverflow, just search for **natural sort**. – Terry Sep 15 '17 at 11:23
  • Possible duplicate of [Sort Array of numeric & alphabetical elements (Natural Sort)](https://stackoverflow.com/questions/4373018/sort-array-of-numeric-alphabetical-elements-natural-sort) – Terry Sep 15 '17 at 11:24

3 Answers3

4

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>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Because comparison is done from left to right, you can try to pad numbers with zeros like a 01, a 02, a 03, a 11

Joern Boegeholz
  • 533
  • 1
  • 8
  • 25
0

@Nenad nailed it: 'kn' does not seem to work, use option numeric in .localeCompare() like:

.localeCompare(jQuery('td:first', b).text(),'en',{numeric:true});

This will take care of the numbering problem. See here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43