Numeric Array Sort
Join the Discussion
Related Resources
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 numOrdD(a, b){ return (b-a); }
We can now sort the array numerically. The following example shows how:
numArray.sort( numOrdA );
document.write('Ascending : ' + numArray + '<br />');
numArray.sort( numOrdD );
document.write('Descending : ' + numArray + '<br />');

