I'm going over this sorting tutorial and I'm having problems understanding it.
I see that the rules are the following when passing in a sortfunction to .sort().
- Less than 0: Sort "a" to be a lower index than "b"
- Zero: "a" and "b" should be considered equal, and no sorting performed.
- Greater than 0: Sort "b" to be a lower index than "a".
and I'm testing this snippet:
var myarray=[25, 8, 7, 41];
console.log(myarray);
console.log(myarray.sort(function(a,b) {
console.log("a : " , a , " b : " , b, " oper : " , b-a, " arr ");
return b -a
}));
the main part is return b -a and this should return the array in descending order I think because if b is larger than a it will be placed in a lower index. I think I'm having a hard time under standing what exactly "lower" means. does it mean that it b goes directly before a or does b go to the beginning of the array?
here is where I'm getting confused. The result of the code is:
[25, 8, 7, 41]
a : 25 b : 8 oper : -17 arr
a : 8 b : 7 oper : -1 arr
a : 7 b : 41 oper : 34 arr
a : 25 b : 41 oper : 16 arr
[41, 25, 8, 7]
here is just my thinking
since the first 2 comparisons produce a negative a goes before b so at the end of the first 2 comparisons the array should be something like [25,8,7,41] (no change).
Then the next comparison is a positive number(34) so so I think b goes before a so it will be now [25,8,41,7] then I don't why it compares 25 and 41 next How is a = 25 and b = 41? can you also show me how to view the array as it is being transformed I tried to do that without success. Thanks in advance.
If you see another question that explains this sorting breakdown in detail I'll be happy to close this question. I don't mean to ask useless questions on SO. most tuts just explain how to sort in general but not break it down. Thank you
.sort()does all it's comparisons is implementation specific and not part of any specification. The point is merely that it uses some algorithm to compare elements in the array and uses your callback function in order to get the result of comparing two elements.