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

100
Vistas
Ordering based on array of objects

I have to define a property sort of an array, using based an array of other objects that have 2 properties called source and target, where the source is the first element and target will be the right next.

My current array is filled in this way:

[{"id":25075,"sort":1},{"id":25076,"sort":2},{"id":25077,"sort":null}]

But based on the source target that I have it should be like this

[{"id":25075,"sort":1},{"id":25076,"sort":3},{"id":25077,"sort":2}]

For a better understanding the source target I have is it:

[{"source":25075,"target":25077},{"source":25077,"target":25076}]

Does somebody know what would be the best way to handle it?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

That's is what you are looking for ?

const array = [
  { source: 25075, target: 25077 },
  { source: 25077, target: 25076 },
];

const result = array.reduce((acc, { source, target }, index) => {
  if (array.length && array.length > index + 1) {
    return [...acc, { id: source, sort: index + 1 }];
  } else if (array.length) {
    return [
      ...acc,
      { id: source, sort: index + 1 },
      { id: target, sort: index + 2 },
    ];
  }

  return acc;
}, []);

console.log("result", result);

At the end we will have the { id: value, sort: position } array you are looking for ?

This code doesn't handle all the cases (with duplicate or other stuff ;))

about 4 years ago · Juan Pablo Isaza Denunciar

0

I don't really understand your problem but is that solving the issue ?

const array = [
  { id: 25075, sort: 1 },
  { id: 25076, sort: 3 },
  { id: 25077, sort: 2 },
];
const result = [];

array.sort((a, b) => (a.sort < b.sort ? -1 : 1));
array.map((v, index) => {
  if (array.length > index + 1) {
    result.push({ source: v.id, target: array[index + 1].id });
  }
});
console.log("result", result);

Instead of the map you can also use reduce and fill an accumulator.

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