简体   繁体   中英

Javascript: sorting objects

I'm looking for some ideas of how to accomplish this as I am hitting a wall on it.

I have a table that displays data pulled from a MySQL db. The table goes in a sequence of a row of 13 cells with displayed data followed by a hidden row of one cell. The hidden row is toggled by clicking a link in cell index 1 of the previous row. Like so:

row 1 : click this cell to show row 2 : another cell : another cell : ad nauseum till we get to 13 : row 2 which is hidden row 3 : click this cell to show row 2 : another cell : another cell : ad nauseum till we get to 13 : row 4 which is hidden ...

so using jquery I pulled all the rows, then set a test to determine if it was a displayed row or hidden row, if it was displayed then I put that row and the following one into an object and then placed that object into another object, like so:

//this function is for sorting the data in the table
$(".sort").click(function() { 

        //get what column we are sorting by
        var sortBy = $(this).attr('sortBy');

        //set the colnum to sort by 
        if (sortBy == "itemname") { 
            var sortCol = 1;
        } else if (sortBy == "priority") { 
            var sortCol = 2;
        } else if (sortBy == "livedate") { 
            var sortCol = 10;
        } else if (sortBy == "status") { 
            var sortCol = 11;
        } else if (sortBy == "designer") { 
            var sortCol = 12;
        } 

        //get the table data
        var tableData = getTableData("NO", "null", "YES", sortBy); 

        //get all the rows
        var tableRowArray = $("#productTableBody tr");

        //declare new table object
        var tableObj = new Object;
        var rowPackage = new Object;

        //loop through tableRowArray and put rows into packages of two, the main row and the hidden row
        for(var t=0; t<tableRowArray.length; t++) { 
            if($(tableRowArray[t]).children(":first").attr('class') == "colorCode") { 

                rowPackage[t] = $(tableRowArray[t]).children();
                rowPackage[t+1] = $(tableRowArray[t+1]).children();

                //dump rows into tableObj
                tableObj[t] = rowPackage;
            }

            //clean out rowPackage
            rowPackage = {};
        }


        var x=-2;
        for(thisRow in tableObj) {
            x = x+2;
            var sortItem = $(tableObj[thisRow][x][sortCol]).html();

                            //ack! -->getting stumped here

        }       
    });

I've also collected which column the user wants to sort by. I can then find the cell the user wants to sort by. I know I need to pull that info, put into an array and sort but I guess I am getting stumped on how to apply the sorted array back to my tableObj so I can rewrite the table body HTML...the reason I am getting stumped is that some of the data to be sorted will be identical, for example if sorting by designer the data could be this {"a", "b", "c", "c", "a", "a", ""a"}, which when sorted would be a, a, a, a, b, c, c, but since some are identical I can't go back and loop through the object and find the entry that matches the first item in my sorted array, 4 items will match it. So how do I determine which entry in the object matches up with the first a in the sorted list?

Thanks in advance.

That's a tough one, but I suppose there is hardly anything impossible in this life.

I would go like this (using Underscore library )

var packs = [];
// assuming you always have even number of tr's
$("#productTableBody tr:odd").each(function(i, tr){
    packs.push( {main: tr, sub: tr.next()} ); 
    // tr.next() will be :even, so it's not yet selected

    // now detach rows from the table
    // note the order - next() wont work otherwise
    tr.next().remove();
    tr.remove();
});

var sortedPacks = _(packs).sortBy(function(pack){
    return $(pack.main).find('td:nth('+sortCol')').text();
});

// now in sortedPacks you have touples of rows sorted by "main" rows sortCol column
// and you would probably want to restore the table now
$.each(packs, function(i, pack){
    $("#productTableBody").append(pack.main).append(pack.sub);
});

The code may not reflect your situation perfectly, but I suppose you should be able to get the main idea.

Not really to easy to get what you are asking for here, but this will at least enable you to get the data sorted.

Start by collecting your data into an array, eg data , each row can be represented by either an array or an object.

Now simply call

data.sort(function(a, b){
     // select the two values from a and b depending on the column to sort by
     a = a[colNr];
     b = b[colNr];
     return a == b ? 0 : a < b ? -1 : 1;
 });

Now you can easily rebuild your table based on the sorted array.

If you during data-collection also added a reference to the row to the array/object, then you can now remove all rows from the table, loop over the data array, and add each node back to the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM