-1

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
JK2018
  • 429
  • 1
  • 9
  • 23
  • links.sort((a,b) => a.orig.src - b.orig.src); Does not seem to work aither – JK2018 May 18 '22 at 14:00
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – jarmod May 18 '22 at 14:06
  • Unfortunatelly no, the example in that post is for an array of objects. But in my case it is an array of objects that have other objects nested inside. I need to sort by the inner object's property value – JK2018 May 18 '22 at 14:10

1 Answers1

1

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);
jarmod
  • 71,565
  • 16
  • 115
  • 122