gpt4 book ai didi

javascript - 如何按对象两个值对对象数组进行排序?

转载 作者:行者123 更新时间:2023-12-03 07:16:21 24 4
gpt4 key购买 nike

我有对象数组:

[{
user: "userName1",
roles: [7,4]
},
{
user: "userName2",
roles: [0,3]
},
{
user: "userName4",
roles: [7,2]
},
{
user: "userName3",
roles: [6,5]
}]

我需要按 roles 对该数组进行排序。第一 roles[0]然后roles[1] .

我的结果必须按如下方式排序:

0. userName1
1. userName4
2. userName3
3. userName2

最佳答案

var data = [{ user: "userName1", roles: [7,4] }, { user: "userName2", roles: [0,3] }, { user: "userName4", roles: [7,2] }, { user: "userName3", roles: [6,5] }];

data.sort(function(a,b) {
if(a.roles[0] == b.roles[0]) return b.roles[1] - a.roles[1];
return b.roles[0] - a.roles[0];
});


document.write('<pre>'+JSON.stringify(data,0,2) + '</pre>');

关于javascript - 如何按对象两个值对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407981/

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