Javascript sorting array

My array is not sorted properly. Can someone tell me what I'm 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 journal shows them in the same order in which they were entered.

+5
source share
4 answers

You want to make a comparison of its kind, not 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 the toLowerCase()Google Link to be placed accordingly.

EDIT: Updated to fix the comparison problem according to the comment .

See example →

+10
source

You are trying to sort by subtracting the lines you get to NaN.

+7

, "a-b" , , NaN. , ( , , ), :

    if (dir == "asc") { 
        sortArray.sort(function(a,b){return a < b ? -1 : 1}); 
    } else { 
        sortArray.sort(function(a,b){return b < a ? -1 : 1});
    }
+6

- NaN, - , .

, , :

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

localeCompare:

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

, . "L" < "a" "l" > "a"

+6

All Articles