views:

182

answers:

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

How to sort by row['key']?

+2  A: 

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.

cjstehno
A: 

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.

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

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(x.a, y.a) < cmp(y.a, x.a) ? -1:1;
});

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

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

To get an ascending sort, use "cmp(...)", and to get a descending sort, use "-cmp(...)"

Mic