CancelImage Upload

How to sort a numeric array in JavaScript

As previously discussed, all that is required in order to sort an array in JavaScript is to define the function sort(), after the array that requires putting in order. However, a bit of trickery is required to indeed sort a numeric array according to it's numeric values.

This is because the array sort functions in JavaScript only look at the first character of a number. In this sense the number 1000 would be listed as lower than the number 2, simply because it starts with a one.

To work around this we will need to define an extra function that calculates the difference between the numbers, based on which it can then make a decision. Here is how It's done:

<title>How to sort a numeric array in JavaScript</title>
<script type="text/javascript">

function sortBySize(number1, number2)

       return number1 - number2;


function sortNumericArray()

       //Returning the unsorted array:

       var numbers = new Array('3', '10', '5', '299', '1', '77');

       var numberList = numbers.join(", ");

       document.getElementById("unSorted").innerHTML = numberList;

       //Sorting the array alphabetically:

       numbersSorted = numbers.sort(sortBySize);

       numberList = numbersSorted.join(", ");

       document.getElementById("sorted").innerHTML = numberList;



<body onload="javascript:sortNumericArray();">

<div id="unSorted"></div>
<div id="sorted"></div>


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •