PruitIgoe PruitIgoe - 1 month ago 7
Javascript Question

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.

Answer

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 →

Comments