数组对象排序、多条件排序如何实现?

let arr = [
    {playerid: 1, score: 120, time: '00:24', count: 24},
    {playerid: 2, score: 110, time: '00:16', count: 16},
    {playerid: 3, score: 120, time: '00:24', count: 23},
    {playerid: 4, score: 105, time: '00:15', count: 16},
    {playerid: 4, score: 105, time: '00:18', count: 13}
]

先根据 score 降序排序,score 值相同的时候再以 count 降序排序
得到结果如下,求一方法

let arr = [
    {playerid: 1, score: 120, time: '00:24', count: 24},
    {playerid: 3, score: 120, time: '00:24', count: 23},
    {playerid: 2, score: 110, time: '00:16', count: 16},
    {playerid: 4, score: 105, time: '00:15', count: 16},
    {playerid: 4, score: 105, time: '00:18', count: 13}
]
阅读 2.7k
2 个回答

一行代码搞定~

let arr = [
    {playerid: 1, score: 120, time: '00:24', count: 24},
    {playerid: 2, score: 110, time: '00:16', count: 16},
    {playerid: 3, score: 120, time: '00:24', count: 23},
    {playerid: 4, score: 105, time: '00:15', count: 16},
    {playerid: 4, score: 105, time: '00:18', count: 13}
];

arr.sort((a, b) => b.score === a.score ? b.count - a.count : b.score - a.score);

console.log(arr);

image.png

arr.sort((x, y) => y.score - x.score || y.count - x.count) 

听说有人写得比我简洁,这是不可以的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏