如何实现
ORDER BY sort1 DESC, sort2 DESCJSON数组中的逻辑如下:
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);