JavaScript 按多个(数字)字段对数组进行排序 [英] JavaScript sort array by multiple (number) fields

查看:31
本文介绍了JavaScript 按多个(数字)字段对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何实现

 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).

逻辑很简单:如果 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆