gpt4 book ai didi

javascript - 按升序和降序对多个数组键进行排序,带数字的字符串

转载 作者:行者123 更新时间:2023-11-30 08:23:00 25 4
gpt4 key购买 nike

我有一个 JavaScript 对象数组:

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

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

最佳答案

您必须将逻辑 || operatorlocaleCompare 函数结合使用。

如果 b.count - a.count 结果为 0

|| 运算符将只考虑第二个分量。

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

关于javascript - 按升序和降序对多个数组键进行排序,带数字的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com