Home > database >  Javascript - remove element from an array if the id in parent of an element is also in the array
Javascript - remove element from an array if the id in parent of an element is also in the array

Time:09-27

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?

CodePudding user response:

First get an array of all id's using map().

Then use filter() to remove those where some() does not includes() in allIds

let data = [{id: "1", parentIds: [] }, {id: "2", parentIds: [] }, {id: "3", parentIds: ["1"] }, {id: "4", parentIds: ["1", "3"] }, {id: "5", parentIds: ["6"] } ];

const allIds = data.map(d => d.id);

data = data.filter((d, x) => !d.parentIds.some(a => allIds.includes(a)));

console.log(data);

CodePudding user response:

You need to .filter your data, to remove all items where .some of the parentIds are found in your data:

const data = [
  { id: "1", parentIds: [] },
  { id: "2", parentIds: [] },
  { id: "3", parentIds: ["1"] },
  { id: "4", parentIds: ["1", "3"] },
  { id: "5", parentIds: ["6"] }
];

const result = data.filter(
  row => !row.parentIds.some(
    id => data.some(d => d.id === id)
  )
);
      
console.log(result);

CodePudding user response:

First extract an array of ids in the original array:

const ids = data.map(el => el.id)

Then filter the original array intersecting each element's parents array with the extracted ids array:

data.filter(el => el.parentIds.filter(parentId => ids.includes(parentId)).length === 0);

See this question Simplest code for array intersection in javascript for an explanation of how array intersection works.

  • Related