patternjavascriptCritical
Sorting an array of objects by property values
Viewed 0 times
arraypropertysortingobjectsvalues
Problem
I've got the following objects using AJAX and stored them in an array:
How do I create a function to sort the objects by the
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 JavaScript only?Solution
Sort homes by price in ascending order:
Or after ES6 version:
Some documentation can be found here.
For descending order, you may use
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
Or after ES6 version:
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));Some documentation can be found here.
For descending order, you may use
homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));Code Snippets
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));Context
Stack Overflow Q#979256, score: 2229
Revisions (0)
No revisions yet.