I am having some difficulties in what the best way to go about this is.
Example below:
const arr = [{
parentId: 1,
children: [
{ childId: 11 },
{ childId: 21 },
{ childId: 31 },
]
}, {
parentId: 31,
children: [
{ childId: 111 },
{ childId: 211 },
{ childId: 311 },
]
}, {
parentId: 7,
children: [
{ childId: 711 },
{ childId: 721 },
{ childId: 731 },
]
}, {
parentId: 311,
children: [
{ childId: 3111 },
{ childId: 3211 },
{ childId: 3311 },
]
}]
So, say I want to remove parentId = 1 then I would like to remove all its assoicated children and if the associated children also is a parentId then their subsequent children as well. Therefore, parentIds 11, 21, 31. 31 is a parentId so remove its childIds – 111, 211 and 311. 311 is a parentId so remove its childIds. No childIds as parentIds fr 311 so we can stop there.
Please if anyone is able to advise best way to go about it. I was thinking recursion but the examples I have seen is more for nested arrays rather than children then separate arrays and repeat the process.
So we would be left with
[{
parentId: 7,
children: [
{ childId: 711 },
{ childId: 721 },
{ childId: 731 },
]
}]
5
Answers
One possibility is to have a queue of ids-to-delete, delete an id on the top of the queue and append all dependent ids. For convenience, let’s also convert your array to a map id->object:
You need no recursion, because of the sorted and flat data and you could filter with a closure over a
Set
where allchildId
are collected.You can use recursion to solve this.
A possibility using recursion and the Ramda.js library:
Using a functional-programming style like this I find makes the code easier to follow (in the long-run!). It tends to encourage using immutable data structures too, so there’s less risk of unintended consequences through modification. It’s not necessarily the most efficient at run-time though.
You can use this approach with
lodash
and recursion: