0

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.

Code Tree
  • 2,160
  • 4
  • 26
  • 39
  • 1
    if that's really how `list` is declared, it would definitely have a `.sort()` method. It doesn't much matter because there's only one item in the array, so it's already sorted. – Pointy Jan 25 '19 at 16:40
  • 1
    If you're trying to do `list[0].sort(...)` well that won't work; there's no `.sort()` method on objects because you can't impose your own ordering on object property names. – Pointy Jan 25 '19 at 16:42
  • 3
    That's not an array of objects it's an array of one object! – Melchia Jan 25 '19 at 16:42
  • oh! sorry..I will edit that question – Code Tree Jan 25 '19 at 16:50
  • Possible duplicate of [Sorting JavaScript Object by property value](https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value) – inorganik Jan 25 '19 at 19:38

2 Answers2

2

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);
antonku
  • 7,377
  • 2
  • 15
  • 21
1

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]);
Melchia
  • 22,578
  • 22
  • 103
  • 117