Sort an array of objects based on property values
P粉561749334
2023-08-21 12:42:00
<p>I obtained the following objects using AJAX and stored them in an array: </p>
<pre class="brush:php;toolbar:false;">var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "Texas",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Beverly Hills",
"state": "California",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "New York State",
"zip": "00010",
"price": "962500"
}
];</pre>
<p>How can I create a function using JavaScript that sorts objects in ascending<strong> or </strong>descending order using only the <code>price</code> property? </p>
This is a more flexible version that allows you to create reusable sort functions and sort by any field.
Sort homes by price in ascending order:
Or after ES6 version:
Some documentation can be found here.
To sort in descending order you can use