How does the following code sort this array in order of numbers?
var array=[25, 8, 7, 41] array.sort(function(a,b){ return a - b })
I know that if the result of the calculation ...
Less than 0 : "a" is sorted as a lower index than "b".
Zero: "a" and "b" are considered equal, and no sorting is performed.
Greater than 0: "b" is sorted as a lower index than "a".
Is the array sort callback function called many times during the sort?
If so, I would like to know which two numbers are passed to the function each time. I assumed that I first took β25β (a) and β8β (b), and then β7β (a) and β41β (b), so:
25 (a) - 8 (b) = 17 (greater than zero, so sort "b" to have a lower index than "a"): 8, 25
7 (a) - 41 (b) = -34 (less than zero, so sort "a" to have a lower index than "b": 7, 41
How are two sets of numbers then sorted in relation to each other?
Please help the struggling newbie!
javascript sorting comparator
cw84 Sep 29 '09 at 20:21 2009-09-29 20:21
source share