Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Sorting a Numeric Array

Since the sort method sorts alphabetically, it won't work with a numeric array—at least not the way you'd expect. If an array contains the numbers 4, 10, 30, and 200, for example, it would sort them as 10, 200, 30, 4—not even close. Fortunately, there's a solution—you can specify a function in the sort method's parameters, and that function will be used to compare the numbers. The following code sorts a numeric array correctly:

function numcompare(a,b) {
   return a-b;
}
nums = new Array(30, 10, 200, 4);
sortednums = nums.sort(numcompare);

This example defines a simple function, numcompare, that subtracts the two numbers. Once you specify this function in the sort method, the array is sorted in the correct numeric order: 4, 10, 30, 200).

Share ThisShare This

Informit Network