Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
Sort an object which is filled with arrays consisting of objects

I am facing an issue where I am getting Api results which I can't modify for my convenience and I have to deal with what I got. I get an object filled with arrays which also have objects inside them similar to this one:

{
sectionOne: [{game: 1, order: 3},{game: 2},{game: 3},{game: 4}],                                                       
sectionTwo: [{game: 1, order: 1},{game: 2},{game: 3},{game: 4}],
sectionThree: [{game: 1, order: 2},{game: 2},{game: 3},{game: 4}],
}

In all sections the first element in the array always has a key called order, which is the position the array needs to be in the object. From the top example, the expected results should be:

{
sectionThree: [{game: 1, order 1},{game: 2},{game: 3},{game: 4}],                                                        
sectionOne: [{game: 1, order 2},{game: 2},{game: 3},{game: 4}],
sectionTwo: [{game: 1, order 3},{game: 2},{game: 3},{game: 4}],
}

PS. I know there isn't a method that can sort objects, I tried mapping them with entries, with keys but I don't know how to go deeper into the structure and target them.

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

You could do this using Array#sort and Destructuring Assignment:

const obj = {
  sectionOne: [{ game: 1, order: 3 }, { game: 2 }, { game: 3 }, { game: 4 }],
  sectionTwo: [{ game: 1, order: 1 }, { game: 2 }, { game: 3 }, { game: 4 }],
  sectionThree: [{ game: 1, order: 2 }, { game: 2 }, { game: 3 }, { game: 4 }],
};

let sortedObj = Object.fromEntries(
  Object.entries(obj).sort(
    ([, [{ order: o1 }]], [, [{ order: o2 }]]) => o1 - o2
  )
);

console.log(sortedObj);

about 4 years ago · Santiago Gelvez Relatório

0

Does this work for you?

arr = arr.sort((a, b) => a[0].order - b[0].order)
about 4 years ago · Santiago Gelvez Relatório

0

If I understood right you need function like:

const sortKeys = (obj) => {
return Object.keys(obj).sort().reduce((acc, key) => {
    acc[key] = obj[key];
    return acc;
}, {});}
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda