1. Home
  2. Computing & Technology
  3. JavaScript

Numeric Array Sort

Join the Discussion

Questions? Comments?

When you sort an array in Javascript the array gets sorted into dictionary order. This means that '30' is less than '4' and gets sorted that way. If your array consists entirely of numbers then you probably want to sort numerically instead. We can change the way that the array sort method works by passing it a parameter identifying a function that contains the instructions on how to compare the entries.

To sort an array into numeric order add the following code (into the head section of your page is probably the most appropriate place):

function numOrdA(a, b){ return (a-b); }
function numOrdD(a, b){ return (b-a); }

We can now sort the array numerically. The following example shows how:

numArray = new Array(3,5,12,53,12,47);
numArray.sort( numOrdA );
document.write('Ascending : ' + numArray + '<br />');
numArray.sort( numOrdD );
document.write('Descending : ' + numArray + '<br />');
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.