From this original question, how would I apply a sort on multiple fields?
Using this slightly adapted structure, how would I sort city (ascending) & then price (
This is a complete cheat but I think that it adds value to this question because it's basically a canned library function that you can use out-of-the box.
If your code has access to lodash
or a lodash compatible library like underscore
then you can use the _.sortBy
method. The snippet below is copied directly from the lodash documentation.
The commented results in the examples looks like they return arrays of arrays but that's just showing the order and not the actual results which are an array of objects.
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(users, [function(o) { return o.user; }]);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]