How to Sort an Array of Objects by Multiple Fields
Sorting an array of objects by multiple fields can be achieved by chaining multiple comparison functions.
Example
Consider the following array of objects representing homes:
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 by city (ascending) and then by price (descending), use the following approach:
homes.sort(function (a, b) { // Compare city fields var cityDelta = a.city.localeCompare(b.city); if (cityDelta !== 0) { // If cities differ, return comparison result return cityDelta; } // If cities are the same, compare prices in descending order return b.price - a.price; });
General Approach
This approach can be generalized to any number of sorting fields. Iterate through the desired sorting fields in the desired order, and compare the values for each field. If a non-zero delta is found, return the result; otherwise, continue to the next field.
The above is the detailed content of How to Sort an Array of Objects by Multiple Fields?. For more information, please follow other related articles on the PHP Chinese website!