Sorting an array in numerical order

by Sanju 2009-12-17 15:06:19

Sorting an array in numerical order

To sort an array in numerical order, use the function array.sort().

var myarray=[25, 101, 10, 33]
myarray.sort() //Array now becomes [10, 101, 25, 33]


The above code will see only the first number. So it returns the result as 10, 101, 25, 33

To Sort numerically and ascending use the below code:

var myarray=[25, 101, 10, 33]
myarray.sort(function(a,b){return a - b}) //Array now becomes [10, 25, 33, 101]


To sort an array in numerical order, simply pass a custom sortfunction into array.sort() that returns the difference between "a" and "b", the two parameters indirectly/ automatically fed into the function.

Tagged in:

1121
like
0
dislike
0
mail
flag

You must LOGIN to add comments