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

时间:2018-05-16 10:38:11

标签: javascript arrays sorting

我有一个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))方法对排序计数。但是,无法弄清楚如何对对象的两个键进行排序。

2 个答案:

答案 0 :(得分:3)

您必须结合||功能使用逻辑localeCompare 运算符

如果||结果 0

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




答案 1 :(得分: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;
}));