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 (descending)?
var homes = [
{"h_id":"3",
"city":"Dallas",
"state":"TX",
"zip":"75201",
"price":"162500"},
{"h_id":"4",
"city":"Bevery Hills",
"state":"CA",
"zip":"90210",
"price":"319250"},
{"h_id":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
I liked the fact than an answer was given which provided a general approach. Where I plan to use this code, I will have to sort dates as well as other things. The ability to "prime" the object seemed handy, if not a little cumbersome.
I've tried to build this answer into a nice generic example, but I'm not having much luck.
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.
Here's an extensible way to sort by multiple fields.
Notes
a.localeCompare(b)
is universally supported and returns -1,0,1 ifa<b
,a==b
,a>b
respectively.||
in the last line givescity
priority overprice
.-price_order
var date_order = new Date(left.date) - new Date(right.date);
works like numerics because date math turns into milliseconds since 1970.return city_order || -price_order || date_order;
Here's my solution based on the Schwartzian transform idiom, hope you find it useful.
Here's an example how to use it:
Simpler one:
I like SnowBurnt's approach but it needs a tweak to test for equivalence on city NOT a difference.
Here's another one that's perhaps closer to your idea for the syntax
Demo: http://jsfiddle.net/Nq4dk/2/
Edit: Just for fun, here's a variation that just takes an sql-like string, so you can do
sortObjects(homes, "city, price desc")