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.
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.
toLowerCase()
EDIT: Updated to fix the comparison problem according to the comment .
See example →
You are trying to sort by subtracting the lines you get to NaN.
NaN
, "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}); }
- NaN, - , .
, , :
function(a,b){ return a>b? 1 : (a<b ? -1 : 0); }
localeCompare:
localeCompare
function(a,b){ return a.localeCompare(b); }
, . "L" < "a" "l" > "a"
"L" < "a"
"l" > "a"