9

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

1
  • 5
    a.sort(function(a,b){return a-b;}) Here's a link to some docs. You should become accustomed to doing research on your own. It will only help you.
    – user1106925
    Commented Feb 24, 2012 at 22:15

6 Answers 6

20

Usually works for me:

a.sort((a, b) => a - b);
1
  • Concise and to the point using simple maths and >1 = 1 && <-1 = -1 : ) Commented Feb 24, 2012 at 22:16
3

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
});
2
  • 3
    Note, the comparison function can return any value it likes -- only the sign is important. So the whole function could be reduced to return a - b;.
    – cHao
    Commented Feb 24, 2012 at 22:15
  • You are right. This a general purporse solution. Commented Feb 24, 2012 at 22:17
1
<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> 
0

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]
-1

Use a custom sort function.

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

Here is a solution to sort a Javascript array in ascending order

code

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.