Home Java Javascript-array JavaScript array sort numerically
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JavaScript array sort numerically

Advertisement
As in our previous example of sorting array elements alphabetically we have used the default sort method to sort array elements but here in this example of sorting array elements ( numeric elements ).

JavaScript array sort numerically

     

As in our previous example of sorting array elements alphabetically we have used the default sort method to sort array elements but here in this example of sorting array elements ( numeric elements ) we have created a sortNumbers() function which sorts the numbers.

In this example we can see that if we use the default sort() method on the numbers it doesn't sort these numbers correctly. Since it takes these numeric elements as alphabet and therefore we need to define a sorting function for sorting numbers. Given below is the full example code of this example html page:

 

 

 

<html>
<head>
<title>
JavaScript array sort() numerically
</title>
<script type="text/javascript">
var arr = new Array(5);
arr[0]="1";
arr[1]="8";
arr[2]="28";
arr[3]="18";
arr[4]="88";
function sortNumbers(one,two){
return(one-two);
}
document.write("<b>Original Array is </b>=>"+arr+"<br>");
document.write("<b>Sorted array without calling any function is</b>=>"
  +arr.sort()+"<br> ");
document.write("<b>Sorted array after calling sortNumbers function is
  </b>=>"+arr.sort(sortNumbers)+"<br> ");
</script>
</head>
<body bgcolor="#ddcdfd">
<h2>
Implementing sort() method on numbers
</h2>
</body>
</html>

By running this example on your browser you will get the following output:

Download Source Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 5, 2008

Ask Questions?    Discuss: JavaScript array sort numerically   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
WDH
November 24, 2011
Explain the function in argument in details

Why arr.sort(-1) does not work ? Why you need to write a function and return a-b as argument inside sort ? What is the logic? How it is executed ?
DMCA.com