Hope this helps Here's a functional way you can do it using recursion. The numbered bullet points match the numbered comments in the code below.

(base) There is no node so there is nothing left to process; return the result r (induction) There is at least one node. If the node's id or parentid is in the set s, a matching node has been found. Add the node's id to the set and start the search over with the partial result r and the remaining nodes, more. (induction) There is at least one node and it does not match the ids we are searching for. Append the node to the result and continue searching more nodes.

code :

```
const removeFamily =
( id = 0
, [ node, ...more ] = []
, s = new Set ([ id ])
, r = []
) =>
node === undefined
? r // 1
: s .has (node.id) || s .has (node.parentid)
? removeFamily // 2
( id
, [ ...r, ...more ]
, s .add (node.id)
, []
)
: removeFamily // 3
( id
, more
, s
, [ ...r, node ]
)
const nodes =
[ { id: 1, parentid: 0 }
, { id: 2, parentid: 1 }
, { id: 3, parentid: 2 }
, { id: 4, parentid: 2 }
, { id: 10, parentid: 4 }
, { id: 5, parentid: 0 }
, { id: 6, parentid: 5 }
, { id: 7, parentid: 7 }
]
const newNodes =
removeFamily (1, nodes)
console .log (newNodes)
// [ { id: 5, parentid: 0 }
// , { id: 6, parentid: 5 }
// , { id: 7, parentid: 7 }
// ]
```

```
const removeFamily =
( id = 0
, [ node, ...more ] = []
, s = new Set ([ id ])
, r = []
) =>
{ if (node === undefined)
return r // 1
else if (s .has (node.id) || s .has (node.parentid))
return removeFamily // 2
( id
, [ ...r, ...more ]
, s .add (node.id)
, []
)
else
return removeFamily // 3
( id
, more
, s
, [ ...r, node ]
)
}
```

```
const recur = (...values) =>
({ recur, values })
const loop = f =>
{ let a = f ()
while (a && a.recur === recur)
a = f (...a.values)
return a
}
const removeFamily = (id = 0, nodes = []) =>
loop
( ( [ node, ...more ] = nodes
, s = new Set ([ id ])
, r = []
) =>
node === undefined
? r // 1
: s .has (node.id) || s .has (node.parentid)
? recur // 2
( [ ...r, ...more ]
, s .add (node.id)
, []
)
: recur // 3
( more
, s
, [ ...r, node ]
)
)
const nodes =
[ { id: 1, parentid: 0 }
, { id: 2, parentid: 1 }
, { id: 3, parentid: 2 }
, { id: 4, parentid: 2 }
, { id: 10, parentid: 4 }
, { id: 5, parentid: 0 }
, { id: 6, parentid: 5 }
, { id: 7, parentid: 7 }
]
const newNodes =
removeFamily (1, nodes)
console .log (newNodes)
// [ { id: 5, parentid: 0 }
// , { id: 6, parentid: 5 }
// , { id: 7, parentid: 7 }
// ]
```