I want to filter an array of objects, recursively based on an input array that filters the values and filters out "empty nodes".
This is an example:
const nodes = [{
value: 'World',
children: [{
value: 'Europe',
children: [{
value: 'BeNeLux',
children: [{
value: 'NL'
}, {
value: 'DE'
}, {
value: 'LU'
}]
}, {
value: 'AL'
}, {
value: 'ZW'
}, {
value: 'UK' // lol
}]
}]
}]
In the array above, nodes have: value and optionally children.
I want a function, that I feed an input array that should filter the values + children of the nodes array as listed above so:
const valuesToBeRemoved = ['NL', 'DE', 'LU', 'ZW', 'UK']
The expected output should then be:
const expectedNodesOutput = [{
value: 'World',
children: [{
value: 'Europe',
children: [{
value: 'AL'
}]
}]
}]
This is what I have tried but it is not working correctly because it's not correctly recursive, and it should filter out nodes that are empty (also curious on how other people come up with a solution that might be cleaner):
const filterNodes = (filter, node) => {
if (node.children) {
const children = node.children
.map(child => filterNodes(filter, child))
.filter(x => x)
if (children.length) {
return {
...node,
children
}
}
} else {
if (!filter.includes(node.value)) {
return node
}
}
}
const getFilteredNodes = (filter, nodes) => {
return filterNodes(filter, { children: nodes })?.children || []
}
Here is a codepen: https://codepen.io/anon/pen/KOXBLe