Skip to content
Advertisement

Javascript – recursively remove nodes of a certain type from tree, but reattach and spread eligible children

I’m writing a recursive function on a JSON tree {name, type, [children]} to remove nodes of a certain type. However, the children of the removed node should get re-attached to the parent, if they are not of the type to be removed.

I’m experiencing the following difficulty: Let’s say I want to remove type b on the following tree:

JavaScript

The original children for parent is [childA, childB, childC]. After the removal, the parent should have children [childA, grandChildA, grandChildB, childC]. However, the result I’m getting is [childA, [grandChildA, grandChildB], childC].

I know I need to spread it out, but I’m not sure where to do it in the recusion.

Here’s the function that I have right now (I know I’m using the spread syntax in the wrong place):

JavaScript

Advertisement

Answer

Updated

I think you can use reduce for that, I’m not having my computer right now to test it, but it’ll be something like this

JavaScript

2nd Update

Code reduced:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement