'Group and sort objects [closed]

I would like to sort an object which you can see below. I want to add all the rating properties for each object and sort the object depending on which rating is highest.

So for example, if Intro 1 total rating is equal to 7 and Intro 2 total rating is equal to 3, then Intro 1 should be the first object.

{
  'Intro 2': [
    {
      deckName: 'Test 2',
      rating: 1
    },
    {
      deckName: 'Test 2',
      rating: 2
    }
  ],
  'Intro 1': [
    {
      deckName: 'Test 1',
      rating: 3
    },
    {
      deckName: 'Test 1',
      rating: 4
    }
  ]
}


Solution 1:[1]

Here's your data

const data = {
  "Intro 2": [
    {
      deckName: "Test 2",
      rating: 1
    },
    {
      deckName: "Test 2",
      rating: 2
    }
  ],
  "Intro 1": [
    {
      deckName: "Test 1",
      rating: 3
    },
    {
      deckName: "Test 1",
      rating: 4
    }
  ]
};

Let's convert it into array and sort through

const dataArr = Object.entries(data);

const sorted = dataArr.sort(
  (a, b) =>
    b[1].reduce((acc, curr) => {
      return acc + curr.rating;
    }, 0) -
    a[1].reduce((acc, curr) => {
      return acc + curr.rating;
    }, 0)
);

And finally converting the array back to object

const obj = {};

sorted.forEach((item) => {
  obj[item[0]] = item[1];
});

Code Sandbox: https://codesandbox.io/s/sleepy-ramanujan-dwzwjm?file=/src/index.js

UPDATE
For the last cycle of converting array to object, this can be more elegant solution

const obj = Object.fromEntries(sorted);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1