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

104
Vistas
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 Respuestas
Responde la pregunta

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 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