0

My question is similar to the one found here, but I'd like to sort by string only. Let's say I have the following HTML.

<tbody>
        <tr class="finance" data-order="1">
            <td>John Smith</td>
            <td>Finance</td>
        </tr>
        <tr class="marketing" data-order="2">
            <td>Jane Doe</td>
            <td>Marketing</td>
        </tr>
        <tr class="maintenance" data-order="3">
            <td>Gary Ryan</td>
            <td>Maintenance</td>
        </tr>
        <tr class="dataEntry" data-order="4">
            <td>Damon Watts</td>
            <td>Data Entry</td>
        </tr>
        <tr class="dataEntry" data-order="5">
            <td>Ben Young</td>
            <td>Data Entry</td>
        </tr>
        <tr class="maintenance" data-order="6">
            <td>Calvin Lewis</td>
            <td>Maintenance</td>
        </tr>
    </tbody>

How can I sort by the second td, in ascending or descending order? Right now I have something like this:

//Ascending Order
var tableRows = new Array();
    $("tbody tr").each(function(){
        tableRows.push(this);
    });
    console.log(tableRows);
    tableRows.sort(function(a, b){
        return( //not sure what to do here)
    }
Community
  • 1
  • 1
iaacp
  • 4,655
  • 12
  • 34
  • 39

1 Answers1

1

Just sort them ?

$("tbody tr").sort(function(a, b) {
    var a_txt = $(a).find('td').eq(1).text(),
        b_txt = $(b).find('td').eq(1).text();

    return a_txt.localeCompare(b_txt);
}).appendTo('tbody');

FIDDLE

To switch the order, just do b_txt.localeCompare(a_txt); instead

user3649503
  • 161
  • 5