I have an array full of objects which need to be sorted, however I cannot seem to get this working. Normally I would just do a simple sort() method, which works fine for sorting on a single column, however in this case I need to sort by one column and then by a second.
To try make this easier to understand, let's say I have an array of objects similar to this one:
{ Name: 'Alfred', Total: 4, Project: 'Foobar' }
Now in this example, how would I go about sorting an array of these objects first by Name, and then by Total? I considered doing something like this:
myArray = myArray.sort(function(a,b){return (a.Name + a.Total) > (b.Name + b.Total)});
However I am not sure what is the best method to approach this. Some suggestions would be appreciated.
myArray.sort(function(a,b){
if(a.Name>b.Name){return 1;}
else if(a.Name<b.Name){return -1;}
else{
if(a.Total>b.Total) return 1;
else if(a.Total<b.Total) return -1;
else return 0;
}
});
Minified version:
myArray.sort(function(a,b){return a.Name>b.Name?1:a.Name<b.Name?-1:a.Total>b.Total?1:a.Total<b.Total?-1:0});
myArray = myArray.sort(function(a, b) {
var ret = a.Name.localeCompare(b.Name);
if (ret == 0) {
if (a.Total > b.Total) {
return 1;
} else if (a.Total < b.Total) {
return -1;
}
}
return ret;
});
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