对象数组的多字段排序
如果需要根据对象数组中的多个字段进行排序,可以使用链式排序可以采用的方法。此方法涉及按顺序比较每个字段的值,直到获得非零差异。
实现
考虑以下对象数组:
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"} ];
要根据城市(升序)和价格(降序)对此数组进行排序,请使用以下排序function:
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price; });
说明
排序函数采用回调作为参数,比较两个对象a和b。它返回一个确定元素顺序的值:
示例输出
排序后,homes 数组重新排列如下:
[{ "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" }]
以上是如何在 JavaScript 中使用多个字段对对象数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!