• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Hour 5. Using Strings and Arrays > Sorting a Numeric Array

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);


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint