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.