问题描述
限时送ChatGPT账号..从这个原始问题,我将如何对多个字段应用排序?
From this original question, how would I apply a sort on multiple fields?
使用这种稍微调整的结构,我将如何对城市(升序)和那么价格(降序)?
Using this slightly adapted structure, how would I sort city (ascending) & then price (descending)?
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"}
];
我喜欢这个事实而不是给出了答案这提供了一个通用的方法.在我计划使用此代码的地方,我必须对日期和其他内容进行排序.为对象准备"的能力似乎很方便,如果不是有点麻烦.
I liked the fact than an answer was given which provided a general approach. Where I plan to use this code, I will have to sort dates as well as other things. The ability to "prime" the object seemed handy, if not a little cumbersome.
我尝试构建这个 回答一个不错的通用示例,但我运气不佳.
I've tried to build this answer into a nice generic example, but I'm not having much luck.
推荐答案
您可以使用链式排序方法,通过取值的增量直到达到不等于零的值.
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.
var 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" }];
data.sort(function (a, b) {
return a.city.localeCompare(b.city) || b.price - a.price;
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
或者,使用 es6,简单地:
Or, using es6, simply:
data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
这篇关于如何按多个字段对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论