Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

64
Vistas
Group and sort objects

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
    }
  ]
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda