Home >Web Front-end >JS Tutorial >How to Sort a Multi-Field Array in JavaScript?
Multi-field Array Sorting
In an earlier question, we explored array sorting based on a single field. However, real-world scenarios often require sorting on multiple criteria. This article demonstrates how to adapt that approach for multi-field sorting.
Specific Example: City and Price
Consider the following Homes array where we need to sort 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" } ];
Multi-field Sorting Approach
To sort based on multiple fields, we can use a chained sorting approach that involves comparing the values of the selected fields, one at a time, until we find a difference.
Implementation
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price; });
Explanation
Output
[ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "6", "city": "Dallas", "state": "TX", "zip": "75000", "price": "556699" }, { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ]
This approach provides a flexible solution for sorting arrays on multiple fields. It can be easily modified to accommodate any number of sorting criteria, making it suitable for a wide variety of data manipulation scenarios.
The above is the detailed content of How to Sort a Multi-Field Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!