Here is a generic way to sort an array of objects, with multiple columns:
The magic little secret here is comparing arrays.
var arr = [
{ id:5, name:"Name3" },
{ id:4, name:"Name1" },
{ id:6, name:"Name2" },
{ id:3, name:"Name2" }
];
//sort name ascending then id ascending
arr.sort(function(a, b){
//note the array comparison [...] < [...]
return [a.name, a.id] < [b.name, b.id] ? -1 : 1;
});
Now if you want to have an ascending or descending order we can do that:
//sort name ascending then id descending
function cmp(x, y){ // generic comparison function
return x > y ? 1 : x < y ? -1 : 0;
}
arr.sort(function(a, b){
//note the minus before -cmp, for descending order
return [cmp(a.name, b.name), -cmp(a.id, b.id)]
< [cmp(b.name, a.name), -cmp(b.id, a.id)] ? -1:1;
});
To add other columns to sort on, you can add other items in the array comparison.