开发者

javascript object sorting not working

I have a sort function which was working fine but then I tried to add a toggle bit to it (sort asc/desc) and something broke and I can't figure it out. In the code below sortArray is an array of objects, sortBy is which item in the object to sort by and sortDir is asc or desc. So for example if the user wanted to sort by designers then itemA and itemB would be a.designer and b.designer or as I am using it a[sortBy] b[sortBy]. If I console.log itemA once they are set they look fine, they are exactly what I am expecting.

However, when if I plug this code in:

if (itemA < itemB); //sort string ascending
    console.log("a<b");     
    return -1;
if (itemA > itemB);
    console.log("a>b");
return 1;

all I am getting is a < b

function oSort(sortArray, sortBy, sortDir) {

        //run array sort method for strings
        sortArray.sort(function(a, b) {

            if(sortBy == "itemname" || sortBy == "designer") {

                //set the sort items - this is the key of the objects of the array array{object, object, object}
                if(sortBy == "itemname") { 
                    var itemA = $(a[sortBy]).html().toLowerCase();
                    va开发者_开发知识库r itemB = $(b[sortBy]).html().toLowerCase();
                } else {  
                    var itemA=a[sortBy].toLowerCase(), itemB=b[sortBy].toLowerCase();
                }

                if (itemA < itemB); //sort string ascending
                    return -1;
                if (itemA > itemB);
                    return 1;

                return 0 //default return value (no sorting)


            } else { 

                if(sortBy == "priority") { 
                    var itemA = $(a[sortBy]).length;
                    var itemB = $(b[sortBy]).length;
                } else if (sortBy == "livedate") { 
                    var itemA = a[sortBy].replace(/\//g, "");
                    var itemB = b[sortBy].replace(/\//g, "");
                } else if (sortBy == "status") { 
                    var itemA = $(a[sortBy]).val();
                    var itemB = $(b[sortBy]).val();
                }


                if(sortDir == "desc") { 
                    return itemA - itemB;
                } else { 
                    return itemB - itemA; 
                }
            }

        });


        return sortArray;

    }


You have a syntax error:

replace

if (itemA < itemB);

with

if (itemA < itemB)

Ok, not really a syntax error, but an extra semi-colon.


look up .reverse() for arrays in js. Not that that solves the issue, but it could solve your need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜