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
How to sort double objects?

I have an array. The data in the array is in the following format.

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];

I want to sort this data according to order value. Is there any way to do this?

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

0

You can use JS custom sort from Array.prototype.sort(), reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Then you can sort by comparing the two element's order, but you still need to determine it's key/attribute (e.g.: a or b or c)

Here, you can use Object.keys() function and take the first key in the object, reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Here's a working example:

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];



//console.log(test);


test.sort((firstEl, secondEl) => { 
    var key1 = Object.keys(firstEl)[0];
    var key2 = Object.keys(secondEl)[0];
    return firstEl[key1].order - secondEl[key2].order
} );
console.log(test);

Output:

[
  {
    "c": {
      "order": 1
    }
  },
  {
    "b": {
      "order": 10
    }
  },
  {
    "a": {
      "order": 100
    }
  }
]
about 4 years ago · Santiago Gelvez Relatório

0

You can use Object.values to get the first property value and access the order property on that to compare.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
test.sort((a, b)=>Object.values(a)[0].order - Object.values(b)[0].order);
console.log(test);

For a more generalized solution, you can create a key extractor function to get the value to compare by.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
const getOrder = x => Object.values(x)[0].order;
test.sort((a, b)=>getOrder(a) - getOrder(b));
console.log(test);

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