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.

5
  • 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. Commented Jan 25, 2019 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. Commented Jan 25, 2019 at 16:42
  • 3
    That's not an array of objects it's an array of one object! Commented Jan 25, 2019 at 16:42
  • oh! sorry..I will edit that question Commented Jan 25, 2019 at 16:50
  • Possible duplicate of Sorting JavaScript Object by property value Commented Jan 25, 2019 at 19:38

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.