JavaScript按多个(数字)字段排序数组

coi*_*iso 28 javascript sorting json

我该如何实现?

 ORDER BY sort1 DESC, sort2 DESC
Run Code Online (Sandbox Code Playgroud)

JSON数组中的逻辑如下:

    var items = '[
          {
            "sort1": 1,
            "sort2": 3,
            "name" : "a",
          },
          {
            "sort1": 1,
            "sort2": 2,
            "name" : "b",
          },
          {
            "sort1": 2,
            "sort2": 1,
            "name" : "c",
          }
    ]';
Run Code Online (Sandbox Code Playgroud)

产生新订单:

b,a,c
Run Code Online (Sandbox Code Playgroud)

rai*_*7ow 75

你应该相应地设计你的排序功能:

items.sort(function(a, b) {
  return a.sort1 - b.sort1  ||  a.sort2 - b.sort2;
});
Run Code Online (Sandbox Code Playgroud)

(因为||运算符的优先级低于-1,所以不必在此处使用括号).

逻辑很简单:如果a.sort1 - b.sort1expression的计算结果为0(所以这些属性相等),它将继续计算||表达式 - 并返回结果a.sort2 - b.sort2.

作为旁注,你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);
Run Code Online (Sandbox Code Playgroud)

  • 请记住,显式胜于隐式。如果要在_any case_中将值作为字符串比较,请使用[String.localeCompare()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare)代替。`<`是模棱两可的;其结果取决于操作数类型-以及不同的类型。 (2认同)

xhg*_*xhg 6

您可以通过创建通用函数来避免硬编码

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

跑步

items.sort(sortByMultipleKey(['sort1', 'sort2']));
Run Code Online (Sandbox Code Playgroud)

有你

[ { sort1: 1, sort2: 2, name: 'b' },
  { sort1: 1, sort2: 3, name: 'a' },
  { sort1: 2, sort2: 1, name: 'c' } ]
Run Code Online (Sandbox Code Playgroud)