Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sort array

My array isn't being sorted properly. Can someone let me know what I am doing wrong?

...
 sortArray = new Array ("hello", "Link to Google", "zFile", "aFile");

//sort array
        if (dir == "asc") { 
            sortArray.sort(function(a,b){return a - b}); 
        } else { 
            sortArray.sort(function(a,b){return b - a});
        }

        for(var i=0; i<sortArray.length; i++) { 
            console.log(sortArray[i]);
        }

the log is showing them in the same order as they were entered.

like image 333
PruitIgoe Avatar asked Mar 29 '11 17:03

PruitIgoe


4 Answers

You want to make a comparison in your sort, not a subtraction:

if (dir == "asc") {
    sortArray.sort(function(a, b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        return a === b ? 0 : a > b : 1 : -1;  
    });
} else {
    sortArray.sort(function(a, b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        return b === a ? 0 : b > a : 1 : -1;  
    });
}

I also used toLowerCase() so that 'Link to Google' is placed appropriately.

EDIT: Updated to fix comparison issue according to comment.

See example →

like image 186
mVChr Avatar answered Nov 07 '22 16:11

mVChr


You're trying to sort by subtracting strings, to which you'll get NaN.

like image 31
Tim Cooper Avatar answered Nov 07 '22 17:11

Tim Cooper


The trouble is that "a - b" is treating the strings like numbers, which returns NaN. You will get the behavior you are looking for (assuming you are looking for case-sensitive sorts) if you replace your sorts with:

    if (dir == "asc") { 
        sortArray.sort(function(a,b){return a < b ? -1 : 1}); 
    } else { 
        sortArray.sort(function(a,b){return b < a ? -1 : 1});
    }
like image 7
DocMax Avatar answered Nov 07 '22 16:11

DocMax


Your comparator functions returns NaN, since it receives two strings, and performs subtraction, an operation that isn't well-defined on strings.

What you should have is something more like:

function(a,b){
   return a>b? 1 : (a<b ? -1 : 0);
}

or you can use localeCompare:

function(a,b){
   return a.localeCompare(b);
}

Remember to treat case appropriately, e.g. "L" < "a" whilst "l" > "a"

like image 6
davin Avatar answered Nov 07 '22 15:11

davin