David Starkey
David Starkey

Reputation: 1840

Order by sorted array

I have a page that contains a table like the following (automatically sorted by "Name" column)

  Name         Open Num   Total Num
-----------------------------------
Doe, John         0          0
Smith, Sarah      4          3
Tyler, Rose       7          8

The second tr would look like this:

<tr id="1"><td class="N">Smith, Sarah</td><td class="O">4</td><td class="T">3</td></tr>

Where the row ID is a counter (first row = 0, second = 1, third = 2, etc.) and the cell class is to grab the column using jQuery ($(".O") gives Open Num column)

I'm trying to get the table to sort based off of the numerical columns (Open Num and Total Num). So output would look like this (sorted by Open Num or Total Num):

  Name         Open Num   Total Num
-----------------------------------
Tyler, Rose       7          8
Smith, Sarah      4          3
Doe, John         0          0

So far, I store the numbers into an array arrQuick and I store the row number in a different array rowCount. I then use the Quick Sort method to sort the data, at the same time sorting the second array, which works perfectly. So now I have the sorted data and the order that my rows should be in.

The Problem

I cannot figure out how to get the table rows to update correctly.

So far I have this.

for(var i=0;i<rowCount.length;i++){
    var tmpHolder=$("#"+i).html();
    $("#"+i).html($("#"+rowCount[rowCount.length-(i+1)]).html());
    $("#"+rowCount[rowCount.length-(i+1)]).html(tmpHolder);
}

When stepping through I can see that initially the updating is working. However, eventually it gets to some point rows are getting updated to places they shouldn't be and I'm not sure why.

Upvotes: 3

Views: 196

Answers (1)

Ram
Ram

Reputation: 144689

You can sort the rows based on the values of table cells. The following method accepts a className of the cells and sorts the rows based on the text contents of that cells.

$.fn.sortTable = function(cls) {
    this.find('tr').sort(function(a, b){
       return $(a).find('td.'+cls).text() > $(b).find('td.' + cls).text();
    }).appendTo(this.find('tbody'));
}

$('table').sortTable('O');

Updated method for supporting ascending and descending orders.

$.fn.sortTable = function (opt) {
    var sort = typeof opt.sortType !== 'undefined' ? opt.sortType : 'asc',
        cls = opt.cls;
    if (!cls) return;

    var $tr = this.find('tbody').children().sort(function(a, b){
       return $(a).find('.' + cls).text() > $(b).find('.' + cls).text();
    });

    if (sort === 'des') {
       $tr = $tr.toArray().reverse();
    }
    this.find('tbody').append($tr);
}

$('table').sortTable({
    cls: 'N',    // className of the cells
    sortType: 'des'  // order 'asc' || 'des' 
});

http://jsfiddle.net/Af7mG/

Upvotes: 2

Related Questions