Sort numbers properly inside an array by converting string to number - Javascript Array

Javascript examples for Array:sort

Description

Sort numbers properly inside an array by converting string to number

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*from   w ww .ja v a  2s. co m*/
function sortNumber(a,b) {
    return parseInt(a) - parseInt(b);
}
var numArray = ["708", "8", "808"];
numArray.sort(sortNumber);
console.log(numArray[0] + ',' +  numArray[1] + ',' +  numArray[2] );
    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials