var arr = [];
arr.push(row1);
arr.push(row2);
...
arr.push(rown);
How to sort by row['key']
?
ES6 - Array Method sort() sort() method sorts the elements of an array.
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With