Skip to content Skip to sidebar Skip to footer

How To Sort A Javascript Array Of Numbers

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

Solution 1:

Usually works for me:

a.sort(function(a,b){ 
  return a - b;
});

Solution 2:

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
});

Solution 3:

<scripttype="text/javascript">functionsortNumber(a,b)
{
return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));

</script>

Solution 4:

You can pass in a comparator function to sort.

> a.sort(function(a, b) { return a < b ? -1 : a > b ? 1 : 0; });
  [1, 3, 23, 100]

Solution 5:

Use a custom sort function.

a = [1, 23, 100, 3];
a.sort(function(a,b){ return a-b; });

Post a Comment for "How To Sort A Javascript Array Of Numbers"