我有一些对象:
[{
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
答案 0 :(得分:1)
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>');