Sort Numeric Array in JavaScript

A lot of developers get confused with the results while calling the JavaScript sort() method on a numeric array. Let us see an example:

On running this code:

<script type="text/javascript">
arrNum = [23, 15, 17, 4, 9, 18, 22];
document.write("<p>" + arrNum.sort() + "</p>");

you get the following output:


This result is not what you expected right? What is happening here is that the elements are converted to their string equivalent before sorting. Hence the sort is not numerical.

To sort the numeric array, you will need to write a custom sort function as shown below:

<script type="text/javascript">
var arrNum = [23, 15, 17, 4, 9, 18, 22];

function sortNumber(num1, num2) {
return num1 - num2;

document.write("<p>" + arrNum.sort(sortNumber) + "</p>");

The custom function sortNumber() sets the sort index of the parameter passed to it. So if num1 is less than num2, num2 has a higher sort index. If num1 is greater than num2, num1 will have a higher sort index and so on.

The result after sorting is as shown below:


Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: