Forum : how to sort array in descending order?
Brief description  about Online courses   join in Online courses
View Sri Bhargavi  Peesapati 's Profile

how to sort array in descending order?

how to sort an array in descending order?
Asked by Sri Bhargavi Peesapati | Jul 28, 2010 |  Reply now
Replies (2)
View sri-bhargavi peesapati 's Profile
Thank You, Sir
Jul 29, 2010
View teacher siliconindia 's Profile
Hi Sri Bhargavi,

Sort an array (alphabetically and ascending):
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.sort());
</script>
The output of the code above will be:
Apple,Banana,Mango,Orange

Sort numbers (numerically and ascending):
<script type="text/javascript">

function sortNumber(a,b)
{
return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));

</script>

The output of the code above will be:
1,5,10,25,40,100

Sort numbers (numerically and descending):
<script type="text/javascript">

function sortNumber(a,b)
{
return b - a;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));

</script>

The output of the code above will be:
100,40,25,10,5,1

Regards,
Vishwanath
Jul 28, 2010