JavaScript按多个(数字)字段排序数组 [英] JavaScript sort array by multiple (number) fields
问题描述
如何实现
ORDER BY sort1 DESC, sort2 DESC
JSON数组中的逻辑如下:
logic in an JSON array like such:
var items = '[
{
"sort1": 1,
"sort2": 3,
"name" : "a",
},
{
"sort1": 1,
"sort2": 2,
"name" : "b",
},
{
"sort1": 2,
"sort2": 1,
"name" : "c",
}
]';
产生新订单:
b,a,c
推荐答案
你应该相应地设计你的排序功能:
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).
逻辑很简单:if a.sort1 - b.sort1
表达式求值为0(所以这些属性相等),它将继续评估 ||
表达式 - 并返回 a.sort2 - b.sort2
的结果。
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
.
作为旁注,您的 items
实际上是一个字符串文字,你必须 JSON.parse
才能得到一个数组:
As a sidenote, your items
is actually a string literal, you have to JSON.parse
to get an array:
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);
这篇关于JavaScript按多个(数字)字段排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!