从这个原始问题中,我该如何对多个字段进行排序?
使用这个稍微调整过的结构,我该如何对城市(升序)和价格(降序)进行排序?
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"}
];
我喜欢这个答案提供了一个通用的方法。在我计划使用这段代码的地方,我需要对日期以及其他事物进行排序。如果不考虑有些繁琐,预处理对象的能力似乎很方便。
我尝试将这个答案构建成一个好的通用示例,但是我没有太多的成功。
sort(["first-field", "ASC"], ["second-field", "DSC"]);
。当我尝试添加第一个答案的“primer”逻辑以处理日期、大小写不敏感等时,这变得更加复杂。 - Mikehomes.sort((a, b) =>
…)
,其中a.prop
和b.prop
。a.prop - b.prop
数值排序,a.prop.localeCompare(b.prop)
字典序排序,(b.prop < a.prop) - (a.prop < b.prop)
通用排序。要按降序排序而不是升序,请取反返回值(例如,使用b.prop - a.prop
而不是a.prop - b.prop
)。 - Sebastian Simon