Home >Web Front-end >JS Tutorial >How can I sort an array of objects using multiple fields in JavaScript?
Multi-Field Sorting of Object Arrays
In cases where sorting is required based on multiple fields within an array of objects, a chained sorting approach can be employed. This method involves comparing the values of each field in sequence, until a non-zero difference is obtained.
Implementation
Consider the following array of objects:
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 based on city (ascending) and then price (descending), use the following sort function:
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price; });
Explanation
The sort function takes a callback as an argument, which compares two objects a and b. It returns a value that determines the order of the elements:
Example Output
After sorting, the homes array is rearranged as follows:
[{ "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" }]
The above is the detailed content of How can I sort an array of objects using multiple fields in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!