I read the following objects using Ajax and stored them in an array:
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": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
How do I create a function to sort the objects by the price
property in ascending or descending order using only JavaScript?
Here is a culmination of all answers above.
Fiddle validation: http://jsfiddle.net/bobberino/4qqk3/
For a normal array of elements values only:
For an array of objects:
To sort it you need to create a comparator function taking two arguments. Then call the sort function with that comparator function as follows:
If you want to sort ascending switch the expressions on each side of the minus sign.
Use lodash.sortBy, (instructions using commonjs, you can also just put the script include-tag for the cdn at the top of your html)
Descending order
Ascending order
This is a nice JQuery plug in:
http://plugins.jquery.com/project/sort (Wayback Machine Link)
You will need two function
Then you can apply this to any object property: