Strange questions about sort ()

question:

var a = ["aa","vv","bb"];
a.sort((a,b)=>a>b);//["aa", "vv", "bb"],
var a = ["aa","vv","bb"];
a.sort((a,b)=>a>b?1:-1);//["aa", "bb", "vv"],

Why? is the sort sorted by the return value-1mem1mem0? Doesn"t true,false work?

Jan.28,2022

arr.sort (compare) the basis for judgment the return value of compare (a code b)

  • compare (a, b) < 0 then an is sorted before b
  • compare (a, b) = 0 then the order remains the same (some older browsers don't follow this rule)
  • compare (a, b) > 0 then b comes before a

your problem should appear on chrome . When using the node environment, it is still your first code, but it can be sorted correctly. The difference is that node uses bubble sorting while chrome uses insertion sorting. You can verify it with the following code and test the changes in the output on chrome and node respectively.

  

true and false cannot

Menu