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

100
Visualizações
Sorting an array by nested object value

I have an array with a structure similar to this:

links = [
{
orig:{ src:"A", target:"B"},
source:{},
target:{}
},
{
orig:{ src:"B", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"A"},
source:{},
target:{}
},
{
orig:{ src:"A", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"B"},
source:{},
target:{}
}
]

I need to sort this array on nested values "src" and "target" that are in the "orig" object. It should be sorted alphabetically on "src", and if several "src" with same value then it uses "target" in order to see which one is to be placed before the other.

The desired sorted result should be:

links = [
{
orig:{ src:"A", target:"B"},
source:{},
target:{}
},
{
orig:{ src:"A", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"B", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"A"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"B"},
source:{},
target:{}
}
]

The array I need to sort has over 8 thousand lines. What would be an efficient way to achieve this? I have figured out a "dirty" way to do it with several nested loops, but with 8000 lines in the array it took very long to process. So it is not a viable solution.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's a simple sort on orig.src then on orig.target:

const links = [
  {
    orig: { src: "A", target: "B" },
    source: {},
    target: {},
  },
  {
    orig: { src: "B", target: "C" },
    source: {},
    target: {},
  },
  {
    orig: { src: "C", target: "A" },
    source: {},
    target: {},
  },
  {
    orig: { src: "A", target: "C" },
    source: {},
    target: {},
  },
  {
    orig: { src: "C", target: "B" },
    source: {},
    target: {},
  },
];

links.sort(function (a, b) {
  return (
    a.orig.src.localeCompare(b.orig.src) ||
    a.orig.target.localeCompare(b.orig.target)
  );
});

console.log(links);

about 4 years ago · Juan Pablo Isaza 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