Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Ordenamiento basado en una matriz de objetos

Tengo que definir un tipo de propiedad de una matriz, usando una matriz basada en otros objetos que tienen 2 propiedades llamadas fuente y destino, donde la fuente es el primer elemento y el destino será el siguiente.

Mi matriz actual se llena de esta manera:

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

Pero según el destino de origen que tengo, debería ser así.

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

Para una mejor comprensión, el objetivo fuente que tengo es:

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

¿Alguien sabe cuál sería la mejor manera de manejarlo?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Eso es lo que buscas?

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

Al final, tendremos la matriz { id: value, sort: position } que está buscando.

Este código no maneja todos los casos (con duplicados u otras cosas;))

about 4 years ago · Juan Pablo Isaza Report

0

Realmente no entiendo tu problema, pero ¿eso está resolviendo el problema?

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

En lugar del mapa, también puede usar reduce y llenar un acumulador.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!