I need to sort an array in javascript..
anyone how to do that??
by default the sort method doesn't work with numbers...
I mean:
a = [1, 23, 100, 3]
a.sort()
a values are:
[1, 100, 23, 3]
thanks :)
Usually works for me:
a.sort(function(a,b){
return a - b;
});
So if you write the sorting function, it will work.
[1, 23, 100, 3].sort(function(a, b){
if (a > b)
return 1;
if (a < b)
return -1;
return 0
});
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With