Home > Software engineering >  Sorting an array by nested object value
Sorting an array by nested object value

Time:05-18

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.

CodePudding user response:

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

  • Related