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

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

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