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

104
Views
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 answers
Answer question

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 Report

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