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

How to sort by row['key']?

4 Answers 4

12

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 );
} );
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

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(...)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.