按升序和降序对多个数组键进行排序,使用数字对字符串进行排序

问题描述 投票:1回答:2

我有一个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
2个回答
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;
}));

3
投票

您必须将逻辑||运算符与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)));
© www.soinside.com 2019 - 2024. All rights reserved.