Java Reference
In-Depth Information
The reason for this is that the numbers are converted into strings and then placed in alpha-
betical order.
So how do you sort an array of numerical values? The answer is to provide a callback func-
tion to the sort() method that tells the sort() method how to compare two values, a
and b . The callback function should return the following:
• a negative value if a comes before b
0 if a and b are in the same position
• a positive value if a comes after b
Here is an example of a compareNumbers function that can be used as a callback to sort
function compareNumbers(a,b){
return a-b;
This simply subtracts the two numbers that are being compared, giving a result that is either
negative (if b is bigger than a ), zero (if a and b are the same value), or positive (if a is
bigger than b ). This means that it can be used as a callback to sort the array of numbers
> [1,3,12,5,23,18,7].sort(compareNumbers);
<< [1, 3, 5, 7, 12, 18, 23]
Much better!
Note: Watch Out For Overflows
In some rare instances where an array includes some very large and negative
numbers, an overflow error can occur and the result of a-b becomes smal-
ler than the smallest number that JavaScript is able to cope with. If this is
the case, the following function can be used as a callback instead:
Search WWH ::

Custom Search