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?
I also worked with some kind of rating and multiple fields sort:
Result
Here is a slightly modified version of elegant implementation from the book "JavaScript: The Good Parts".
NOTE: This version of
by
is stable. It preserves the order of the first sort while performing the next chained sort.I have added
isAscending
parameter to it. Also converted it toES6
standards and "newer" good parts as recommended by the author.You can sort ascending as well as descending and chain sort by multiple properties.
For sort on multiple array object field. Enter your field name in
arrprop
array like["a","b","c"]
then pass in second parameterarrsource
actual source we want to sort.for string sorting in case some one needs it,
You can use the JavaScript
sort
method with a callback function:For sorting a array you must define a comparator function. This function always be different on your desired sorting pattern or order(i.e. ascending or descending).
Let create some functions that sort an array ascending or descending and that contains object or string or numeric values.
Sort numbers (alphabetically and ascending):
Sort numbers (alphabetically and descending):
Sort numbers (numerically and ascending):
Sort numbers (numerically and descending):
As above use sorterPriceAsc and sorterPriceDes method with your array with desired key.