0

I need to sort the following object by its keys

const leagues = {
  2020: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
  2021: [{}],
  2022: [{}],
};

To this end try the following

const entries = Object.entries(leagues).sort((a, b) => b[0].localeCompare(a[0]));

I get the expected result

[
  [ '2022', [ {} ] ],
  [ '2021', [ {} ] ],
  [
    '2020',
    [
      {}, {}, {}, {}, {},
      {}, {}, {}, {}, {},
      {}
    ]
  ]
]

Now I want to transform this result into an object again, for this I try the following

const output = Object.fromEntries(entries);

Curiously the output of this call forgets the order

{
  '2020': [
    {}, {}, {}, {}, {},
    {}, {}, {}, {}, {},
    {}
  ],
  '2021': [ {} ],
  '2022': [ {} ]
}

How can I achieve the expected result?

Mario
  • 4,117
  • 1
  • 22
  • 39

0 Answers0