我有一个JavaScript对象数组:
这不是一个重复的问题。
因为,我有一个包含2个键的对象数组(key
,count
)。
我想按降序排序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))
方法对排序计数。但是,无法弄清楚如何对对象的两个键进行排序。
答案 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;
}));