Reputation: 61
I am trying to do a classement for my website in express but for that i would like to sort my value from the most to least like:
user123: 0
user987: 4
user769: 3
and after get:
user987: 4
user769: 3
user123: 0
for that i've tried
classement.sort(function(a, b) {
return a.val - b.val;
})
but it didn't work with classement.sort is not a function
as error
this is what my json look like:
{
'60e300f77c30186d545b2db3': 5,
'60e301c4fc57814fd008017c': 2,
'60e4439ea4025957366959f6': 10,
'60e443bda402595736695a26': 4
}
Upvotes: 0
Views: 54
Reputation: 5695
You're trying to invoke the array method .sort
on an object. You have to convert your JSON response to an array first. Also, as your object entities have different key names you'll have to do some additional mapping in order to handle it properly. You don't have a val
property.
Also, your sorting function should be reversed as you want to sort descending.
Take a look at this solution and modify it as you see fit:
const jsonResponse = {
'60e300f77c30186d545b2db3': 5,
'60e301c4fc57814fd008017c': 2,
'60e4439ea4025957366959f6': 10,
'60e443bda402595736695a26': 4
};
const array = [];
Object.entries(jsonResponse).forEach(item => array.push({
key: item[0],
value: item[1]
}));
array.sort((a, b) => {
return b.value - a.value;
});
Upvotes: 1