【问题标题】:Sort multiple array key's in ascending and descending order, string with number按升序和降序对多个数组键进行排序,字符串与数字
【发布时间】:2018-10-26 09:02:28
【问题描述】:

我有一个 JavaScript 对象数组:

这不是重复的问题。 因为,我有一个包含 2 个键(keycount)的对象数组。 我想排序,key 升序(即 字符串)和 value 降序(即 数字)。

 var array = [
  {"count":7,"key":"a"},
  {"count":10,"key":"b"},
  {"count":5,"key":"c"},
  {"count":10,"key":"a"},
  {"count":3,"key":"d"}
];

期望的输出:

     var array = [
      {"count":10,"key":"a"},
      {"count":10,"key":"b"},
      {"count":7,"key":"a"},
      {"count":5,"key":"c"},
      {"count":3,"key":"d"}
    ];

var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];

console.log(array.sort((a, b) => (b.count - a.count)));

key 排序为升序

count 排序为降序

我已经使用array.sort((a, b) => (b.count - a.count)) 方法进行排序计数。但是,无法弄清楚如何对对象的两个键进行排序。

【问题讨论】:

标签: javascript arrays sorting


【解决方案1】:

您必须将逻辑|| 运算符localeCompare 函数结合使用。

|| 运算符仅在b.count - a.count 结果为时才考虑第二个组件。

var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];

console.log(array.sort((a, b) => b.count - a.count || a.key.localeCompare(b.key)));

【讨论】:

    【解决方案2】:

    尝试关注

    var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];
    
    console.log(array.sort((a, b) => {
      if(a.count === b.count) return a.key.localeCompare(b.key);
      return b.count - a.count;
    }));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2015-08-30
      • 2020-09-16
      • 2017-01-09
      • 1970-01-01
      相关资源
      最近更新 更多