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)
    }
10
  • That depends on whether or not you want locale-aware comparisons. Commented May 21, 2014 at 15:25
  • 1
    I don't think this works: tableRows.push(this); because this is bounded to the global object. Commented May 21, 2014 at 15:26
  • 1
    @iaacp, I mean it depends on whether simple comparison is enough or if you have to use localeCompare(). Commented May 21, 2014 at 15:28
  • 3
    @linstantnoodles, not in the callback passed to each(), no. Commented May 21, 2014 at 15:28
  • 1
    This is more of a sidestep, but declaring arrays as [] in JavaScript is waaaay more efficient that using new Array() Commented May 21, 2014 at 15:29

1 Answer 1

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

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.