I have an array that has parent-child values. I need to remove the elements from the array if its parent is already there in the array.
Sample data:
const data = [
  {
    id: "1",
    parentIds: []
  },
  {
    id: "2",
    parentIds: []
  },
  {
    id: "3",
    parentIds: ["1"]
  },
  {
    id: "4",
    parentIds: ["1", "3"]
  },
  {
    id: "5",
    parentIds: ["6"]
  }
]
The expected output is:
[
  {
    id: "1",
    parentIds: []
  },
  {
    id: "2",
    parentIds: []
  },
  {
    id: "5",
    parentIds: ["6"]
  }
]
I tried with the following code:
for (let i = selectedItems.length - 1; i >= 0; i--) {
      for (let j = selectedItems.length - 1; j >= 0; j--) {
        if (selectedItems[j].parentsIds.includes(selectedItems[i].id)) {
          selectedItems.splice(i, 1)
        }
      }
    }
But this fails with Cannot read properties of undefined (reading 'id') after splicing first match.
It there anyway this can be achieved?
 
     
     
    