-1

I am using sort() function of Array Library in JS. But, I am not getting correct result. Can anyone point out why?

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

var a = [5, 17, 29, 48, 64, 21];
var c = a.sort();
alert(c);

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

Why 5 is not coming in the beginning, but somewhere in middle? Can someone help?

Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

0

By default the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

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

var numArray = [5, 17, 29, 48, 64, 21];
numArray.sort(sortNumber);
alert(numArray.join(","));

Reference : How to sort an array of integers correctly

Farhan Qasim
  • 990
  • 5
  • 18
0

Try this,

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

var a = [5, 17, 29, 48, 64, 21];
var c = a.sort(sortNumber);
Dui Samarasinghe
  • 247
  • 2
  • 10