从这个最初的问题,我将如何在多个字段应用排序?
使用这种稍作调整的结构,我将如何排序城市(上升)和价格(下降)?
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"}
];
我喜欢的事实是,给出的答案提供了一个一般的方法。在我计划使用这段代码的地方,我将不得不对日期以及其他东西进行排序。“启动”对象的能力似乎很方便,如果不是有点麻烦的话。
我试图把这个答案构建成一个很好的通用示例,但我运气不太好。
为了简化操作,可以使用这些辅助函数。
您可以根据需要对任意多个字段进行排序。对于每个排序字段,指定属性名,然后可选地指定-1作为排序方向,以降序排序而不是升序排序。
const data = [
{"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"},
{"h_id":"7","city":"New York","state":"NY","zip":"00010","price":"800500"}
]
const sortLexically = (p,d=1)=>(a,b)=>d * a[p].localeCompare(b[p])
const sortNumerically = (p,d=1)=>(a,b)=>d * (a[p]-b[p])
const sortBy = sorts=>(a,b)=>sorts.reduce((r,s)=>r||s(a,b),0)
// sort first by city, then by price descending
data.sort(sortBy([sortLexically('city'), sortNumerically('price', -1)]))
console.log(data)