I am trying to sort nested array of objects, based off the key hours. The reason I am setting the index as userId, is that I want to be able to do highScoreList[userId] at a later time to grab the selected user information.
[
'587665723162626': { userId: '587665723162626', hours: 0, lastHours: 0 },
'120156769943556': { userId: '120156769943556', hours: 0, lastHours: 0 },
'773193626386432': { userId: '773193626386432', hours: 10, lastHours: 2 }
]
let highScoreList = [];
//data is inserted via another function from mongoDB and below is how I inserted into the array.
const updateHighScoreCache = (userId, hours, lastHours) =>{
highScoreList[userId] = { userId, hours, lastHours };
}
function compare(a, b) {
if(a.hours > b.hours) return 1;
if(b.hours > a.hours) return -1;
return 0;
}
highScoreList.sort(compare)
I have tried changing the if statement in the compare function to the following and the array did not change at all still:
if(highScoreList[a].hours > highScoreList[b].hours) return 1;
if(highScoreList[b].hours > highScoreList[a].hours) return -1;
The expected result after sort is:
[
'773193626386432': { userId: '773193626386432', hours: 10, lastHours: 2 },
'587665723162626': { userId: '587665723162626', hours: 0, lastHours: 0 },
'120156769943556': { userId: '120156769943556', hours: 0, lastHours: 0 }
]
But I keep getting the original array.