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>

2
  • 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. There are also other solutions already available on StackOverflow, just search for natural sort. Commented Sep 15, 2017 at 11:23
  • Possible duplicate of Sort Array of numeric & alphabetical elements (Natural Sort) Commented Sep 15, 2017 at 11:24

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

hey, thanks for your answer. But i want it like 1,2,3 only. can not add 0.
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

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.