Code Tree
Code Tree

Reputation: 2209

sort an object in an array which has string key

I have this array of objects, I need to sort the 'list' by 'score' in descending order by score.

var list =[{ '440684023463804938': { score: 6, bonuscount: 2 },
  '533932209300832266': { score: 20, bonuscount: 0 },
  '448746017987231756': { score: 9, bonuscount: 0 },
  '492585498561216513': { score: 14, bonuscount: 0 } }]

I usually do with .sort function, but this time it gives me list.sort is not a function

Any help is appreciated.

Upvotes: 0

Views: 37

Answers (2)

Melchia
Melchia

Reputation: 24234

If you want to preserve you JSON architecture, starting with your input:

const input = [{ '440684023463804938': { score: 6, bonuscount: 2 },
  '533932209300832266': { score: 20, bonuscount: 0 },
  '448746017987231756': { score: 9, bonuscount: 0 },
  '492585498561216513': { score: 14, bonuscount: 0 } }];
  

const output = Object.keys(input[0]).sort((a,b) => b-a)
      .reduce( (acc , curr) => { 
                acc[curr] = input[0][curr];
                return acc; 
                },
                {});

console.log([output]);

Upvotes: 1

antonku
antonku

Reputation: 7665

You can convert the object to an array and then apply a regular sorting:

const list = [
    {
        '440684023463804938': {score: 6, bonuscount: 2},
        '533932209300832266': {score: 20, bonuscount: 0},
        '448746017987231756': {score: 9, bonuscount: 0},
        '492585498561216513': {score: 14, bonuscount: 0}
    }
];

const result = Object.entries(list[0]).sort((a, b) => b[1].score - a[1].score);

console.log(result);

Upvotes: 2

Related Questions