1

I have example array like this:

let arr = [
{ id: "1325asdfasdasd", next: "5345341fgdfgdd", previous: "545234123fsdfd" },
{ id: "das987as9dya8s", next: "3j12k3b1231jkj" },
{ id: "89ad8sasds9d8s", previous: "1j3b12k3jbasdd" },
{ id: "5345341fgdfgdd", next: "1j3b12k3jbasdd", previous: "1325asdfasdasd" },
{ id: "1423123123asfd", next: "545234123fsdfd", previous: "3j12k3b1231jkj" },
{ id: "1j3b12k3jbasdd", next: "89ad8sasds9d8s", previous: "5345341fgdfgdd" },
{ id: "3j12k3b1231jkj", next: "1423123123asfd", previous: "das987as9dya8s" },
{ id: "545234123fsdfd", next: "1325asdfasdasd", previous: "1423123123asfd" },

]

I'm trying to sort array by "next" and "previous" properties, expecting the result like this:

let arr = [
{ id: "das987as9dya8s", next: "3j12k3b1231jkj" },
{ id: "3j12k3b1231jkj", next: "1423123123asfd", previous: "das987as9dya8s" },
{ id: "1423123123asfd", next: "545234123fsdfd", previous: "3j12k3b1231jkj" },
{ id: "545234123fsdfd", next: "1325asdfasdasd", previous: "1423123123asfd" },
{ id: "1325asdfasdasd", next: "5345341fgdfgdd", previous: "545234123fsdfd" },
{ id: "5345341fgdfgdd", next: "1j3b12k3jbasdd", previous: "1325asdfasdasd" },
{ id: "1j3b12k3jbasdd", next: "89ad8sasds9d8s", previous: "5345341fgdfgdd" },
{ id: "89ad8sasds9d8s", previous: "1j3b12k3jbasdd" },

]

Is there any comparator function to do it? So far I've tried this:

arr.sort((a, b) => {
    if (a.id === b.previous) {
        return -1;
    }
    if (a.id === b.next) {
        return 1;
    }
});

But it doesn't work as expected.

  • That sorting approach doesn't really work. Only neighbouring values are directly comparable, all other values aren't comparable. But `sort` requires a logic where any value can be compared with any other value with each comparison being clearly decidable. – deceze Feb 14 '20 at 11:21
  • That's because sort expects you must always return for two elements if they are A > B, B > A or A == B, but you are not doing so, you are returning erratic values. You must implement your own sort function. – user1039663 Feb 14 '20 at 11:23

0 Answers0