How to sort javascript numbers array

I need to sort an array in javascript ..

anyone how to do this?

by default, the sorting method does not work with numbers ...

I mean:

a = [1, 23, 100, 3]
a.sort()

a values:

[1, 100, 23, 3]

thank:)

+4
source share
6 answers

Usually works for me:

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

So, if you write a sort function, it will work.

[1, 23, 100, 3].sort(function(a, b){
    if (a > b)
        return 1;
    if (a < b)
        return -1;
    return 0
});
+4
source
<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> 
+2

.

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

sort.

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

Javascript

function bubblesort(array){

    var done = false;
    while(!done){
        done = true;
        for(var i = 1; i< array.length; i++){
            if(array[i -1] > array[i]){
                done = false;
                var tmp = array[i-1];
                array[i-1] = array[i];
                array[i] = tmp;
            }
        }
    }
    return array;
}
var numbers = [2, 11, 1, 20, 5, 35];
bubblesort(numbers);
0

All Articles