我有一个如下数组
[{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 144391
},
{
"score": 15,
"time": 900039
},
{
"score": 3,
"time": 143962
}]
我想得到如下结果
[
{
"score": 15,
"time": 900039
},
{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 143962
},
{
"score": 3,
"time": 144391
}]
分数应按降序排序,而相同分数的时间应按升序排序。
newScoreArray.sort(function(a, b) {
if(a.score === b.score) {
var x = a.timeTaken,
y = b.timeTaken;
if(x>y){
return -1;
}else{
return 1;
}
}
return b.score - a.score;
});
但这只是根据分数进行排序。请在这里告诉我我在做什么错。另外,如果您有更好的主意,请帮助我。
答案 0 :(得分:1)
这非常简单
let a = [{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 144391
},
{
"score": 15,
"time": 900039
},
{
"score": 3,
"time": 143962
}]
// for ascending sort
a.sort((a,b) => {
if (a.score == b.score) return a.time - b.time;
return a.score - b.score;
})
// for your case
a.sort((a,b) => {
if (a.score == b.score) return a.time - b.time;
return b.score - a.score;
})
console.log(a)
答案 1 :(得分:0)
或者,如果您想变得简洁:
let a = [{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 144391
},
{
"score": 15,
"time": 900039
},
{
"score": 3,
"time": 143962
}]
a.sort((a,b) => b.score - a.score || a.time - b.time)
console.log(a)
如果分数相等,则b.score - a.score
的值为0(假),因此将使用时间。