Roger Far
Roger Far

Reputation: 2385

Sorting of table

I have looked at many sorting solutions for jQuery but haven't found what I'm looking for yet.

I am trying to sort a table which has rows and columns that need to be sorted: http://jsfiddle.net/rvezE/

<table>
<tr>
    <td>3</td>
    <td>5</td>
    <td>7</td>
</tr>
<tr>
    <td>1</td>
    <td>2</td>
    <td>4</td>
</tr>
<tr>
    <td>3</td>
    <td>8</td>
    <td>9</td>
</tr>
</table>

I need the table to be sorted from left to right, top to bottom. But all plugins I found so far can only sort by row.

I have tried a few simple solution by taking all the TD's out, sorting them and re-adding them, but for a large amount (around 100) the performance is terrible, it needs to be quite snappy for tablets too.

Anyone came across something like this?

Upvotes: 0

Views: 124

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Try this:

/*remove rows from DOM, loop over each row within jQuery object to sort cells*/
var $rows=$('tr').detach().each(function(){
    /* sort cells of this row*/
    var cells=$(this).find('td').sort(function(a,b){
        return $(a).text() >  $(b).text();
    }); 
    /* update sorted html of this row*/
    $(this).html( cells)

})
/* now sort the rows*/
.sort(function(a,b){
     return $(a).find('td').first().text() >  $(b).find('td').first().text();

});
/* update table with sorted rows html*/
$('table').html($rows);

DEMO

Assumes you only want to sort by first column

Upvotes: 2

Related Questions