How to sort an array in javascript?

var arr = [];
arr.push(row1);
arr.push(row2);
...
arr.push(rown);

How to sort by row['key']?

+5
source share
4 answers

The JavaScript array has a built-in method sort(). In this case, the following will work:

arr.sort( function(row1, row2) {
    var k1 = row1["key"], k2 = row2["key"];
    return (k1 > k2) ? 1 : ( (k2 > k1) ? -1 : 0 );
} );
+11
source

You call the array sort function with your comparator. A JavaScript comparator is simply a function that returns -1, 0, or 1, depending on whether a is less than b, a is b, or greater than b:

myarray.sort(function(a,b){
    if(a < b){
        return -1;
    } else if(a == b){
        return 0;
    } else { // a > b
        return 1;
    }
});

This is just an example, your function can base the comparison on what you want, but it needs to return -1,0,1.

Hope this helps.

+4
source

, asending, .

var cmp = function(x, y){ return x > y? 1 : x < y ? -1 : 0; },
    arr =  [{a:0,b:0},{a:2,b:1},{a:1,b:2},{a:2, b:2}];

// sort on column a ascending
arr.sort(function(x, y){
    return cmp( cmp(x.a, y.a), cmp(y.a, x.a) );
});

// sort on column a descending
arr.sort(function(x, y){
    return cmp( -cmp(x.a, y.a), -cmp(y.a, x.a) );
});

// sort on columns a ascending and b descending
arr.sort(function(x, y){
    return cmp([cmp(x.a, y.a), -cmp(x.b, y.b)], [cmp(y.a, x.a), -cmp(y.b,x.b)]);
});

To get an upward sort, use "cmp (...)", and to get a downward sort, use "-cmp (...)"

And to sort by multiple columns, compare two cmp arrays (...)

+2
source

Consider the following code:

var arr = new Array();

for(var i = 0; i < 10; ++i) {
    var nestedArray = [ "test", Math.random() ];
    arr.push(nestedArray);
}

function sortBySecondField(a, b) {
    var aRandom = a[1];
    var bRandom = b[1];

    return ((aRandom < bRandom) ? -1 : ((aRandom > bRandom) ? 1 : 0));
}

arr.sort(sortBySecondField);

alert(arr);

Now just change the function sortBySecondFieldto compare a['key']instead a[1]and do the same for b.

0
source

All Articles