1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

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 />');
Related Video
Microsoft Excel Sort Feature

©2017 About.com. All rights reserved.