Monday, 18 September 2017

javascript - Sorting an array of objects by property values



I've got 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 JavaScript only?


Answer



Sort homes by price in ascending order:




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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...