Sort an Array ascending and descending order in JavaScript

Using JavaScript code to Sort the numbers in array in ascending and descending order

We can make the array ascending and descending order simply using JavaScript's predefined function sort for array.
Just follow the simple real time Example.

//source code for sort array in javascript

<script type="text/javascript">
function sort_Array_Number(a, b)
{
return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sort_Array_Number));
</script>

The above code will show the numbers in array in ascending order. The output will be 1,5,10,25,40,100.

To display the numbers in descending order we can do it by similar format.

<script type="text/javascript">
function sort_Array_Number(a, b)
{
return b - a;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sort_Array_Number));
</script>


In the above code in sort_Array_Number function will return b-a to show the number in descending order. The output will be 100, 40, 25, 10, 5, 1


Related Topic Using array_multisort() to Array Multi-sorting
Bubble Sort in Javascript
PHP Code for Creating Tag Cloud
Ascending and Descending Order DIV Sorting in PHP
Unique random number in Javascript

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback