JavaScript 按多个(数字)字段对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13211709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript sort array by multiple (number) fields
提问by coiso
How can I implement a
我该如何实施
ORDER BY sort1 DESC, sort2 DESC
logic in an JSON array like such:
JSON 数组中的逻辑,如下所示:
var items = '[
{
"sort1": 1,
"sort2": 3,
"name" : "a",
},
{
"sort1": 1,
"sort2": 2,
"name" : "b",
},
{
"sort1": 2,
"sort2": 1,
"name" : "c",
}
]';
resulting in the new order :
导致新订单:
b,a,c
回答by raina77ow
You should design your sorting function accordingly:
您应该相应地设计排序功能:
items.sort(function(a, b) {
return a.sort1 - b.sort1 || a.sort2 - b.sort2;
});
(because ||
operator has lower precedence than -
one, it's not necessary to use parenthesis here).
(因为||
运算符的优先级低于-
1,所以这里没有必要使用括号)。
The logic is simple: if a.sort1 - b.sort1
expression evaluates to 0 (so these properties are equal), it will proceed with evaluating ||
expression - and return the result of a.sort2 - b.sort2
.
逻辑很简单:如果a.sort1 - b.sort1
expression 的计算结果为 0(因此这些属性相等),它将继续计算||
expression - 并返回a.sort2 - b.sort2
.
As a sidenote, your items
is actually a string literal, you have to JSON.parse
to get an array:
作为旁注,您items
实际上是一个字符串文字,您必须JSON.parse
获得一个数组:
const itemsStr = `[{
"sort1": 1,
"sort2": 3,
"name": "a"
},
{
"sort1": 1,
"sort2": 2,
"name": "b"
},
{
"sort1": 2,
"sort2": 1,
"name": "c"
}
]`;
const items = JSON.parse(itemsStr);
items.sort((a, b) => a.sort1 - b.sort1 || a.sort2 - b.sort2);
console.log(items);
回答by xhg
You can avoid hardcoding by create a general function
您可以通过创建通用函数来避免硬编码
function sortByMultipleKey(keys) {
return function(a, b) {
if (keys.length == 0) return 0; // force to equal if keys run out
key = keys[0]; // take out the first key
if (a[key] < b[key]) return -1; // will be 1 if DESC
else if (a[key] > b[key]) return 1; // will be -1 if DESC
else return sortByMultipleKey(keys.slice(1))(a, b);
}
}
Running
跑步
items.sort(sortByMultipleKey(['sort1', 'sort2']));
will have you
会有你
[ { sort1: 1, sort2: 2, name: 'b' },
{ sort1: 1, sort2: 3, name: 'a' },
{ sort1: 2, sort2: 1, name: 'c' } ]
回答by Fernando Lucas Souza
const itemsStr = `[{
"sort1": 1,
"sort2": 3,
"name": "a"
},
{
"sort1": 1,
"sort2": 2,
"name": "b"
},
{
"sort1": 2,
"sort2": 1,
"name": "c"
}
]`;
const items = JSON.parse(itemsStr);
items.sort((a, b) => a.sort1 - b.sort1 || a.sort2 - b.sort2);
console.log(items);