Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a javascript array of numbers [duplicate]

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 :)

like image 595
pahko Avatar asked Feb 24 '12 22:02

pahko


3 Answers

Usually works for me:

a.sort(function(a,b){ 
  return a - b;
});
like image 75
raina77ow Avatar answered Sep 29 '22 12:09

raina77ow


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
});
like image 24
Andrés Torres Marroquín Avatar answered Sep 29 '22 10:09

Andrés Torres Marroquín


<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> 
like image 32
Sid Avatar answered Sep 29 '22 10:09

Sid