Home >Web Front-end >JS Tutorial >How Can I Sort an Array of Objects by Multiple Fields in JavaScript?
Sorting Arrays of Objects by Multiple Fields
In the original question, sorting an array of objects by a single field was solved efficiently. However, how can we apply a sort on multiple fields?
To sort an array of objects by multiple fields, we can use a chained sorting approach. This involves sorting by the first field and then, if the values are equal, continuing to sort by the second field. If necessary, this process can be repeated for more fields.
Consider the following example where we want to sort an array of homes by city (ascending) and then price (descending):
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":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"}, {"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"} ];
To sort this array, we can use the following JavaScript code:
homes.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price; });
Here's how this code works:
By applying this sorting approach to multiple fields, we can easily sort complex arrays of objects in the desired order.
The above is the detailed content of How Can I Sort an Array of Objects by Multiple Fields in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!