I have an array like following
[{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 144391
},
{
"score": 15,
"time": 900039
},
{
"score": 3,
"time": 143962
}]
I want to have the result like the following
[
{
"score": 15,
"time": 900039
},
{
"score": 12,
"time": 97192
},
{
"score": 3,
"time": 143962
},
{
"score": 3,
"time": 144391
}]
The score should be sorted in descending order while the time for the same score should be sorted in ascending order.
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;
});
But this is just sorting according to the score only. Please suggest me what I am doing wrong here. Also if you have a better idea then please help me with it.