Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array in javascript?

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

How to sort by row['key']?

like image 631
user198729 Avatar asked Feb 02 '10 15:02

user198729


People also ask

How do I sort an array in ES6?

ES6 - Array Method sort() sort() method sorts the elements of an array.

What does arrays sort () do?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.


2 Answers

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 );
} );
like image 198
Tim Down Avatar answered Sep 18 '22 16:09

Tim Down


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.

like image 20
cjstehno Avatar answered Sep 20 '22 16:09

cjstehno