开发者

How to sort array in javascript?

var arr = [];
arr.push(row1);开发者_如何学C
arr.push(row2);
...
arr.push(rown);

How to sort by row['key']?


A JavaScript array has a built-in sort() method. In this case, something like the following would work:

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


You call the sort function of an array with your comparator. A JavaScript comparator is just a function that returns -1, 0, or 1 depending on whether a is less than b, a is equal to b, or a is 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 whatever you want, but it needs to return -1,0,1.

Hope this helps.


Here is set of functions if you want to sort asending, descending, or sort on multiple columns in an array.

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 ascending sort, use "cmp(...)", and to get a descending sort, use "-cmp(...)"

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


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 a sortBySecondField function to compare a['key'] instead of a[1] and do the same for b.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜