for the requirements on the front end, you need to write a search function to traverse the tree,
function search(nodes, keyword){
// `const nodes`
}
const searchedNodes = search(nodes, "1-1-2-1");
// "1-1-2-1"
/*
searchedNodes
[
{
value: "1-1",
children: [
{ value: "1-1-2", children:[
{
value: "1-1-2-1",
children: [
{ value: "1-1-2-1-1" }
]
}
] }
]
}
]
*/
const nodes = [
{
value: "1-1",
children: [
{ value: "1-1-1"},
{ value: "1-1-2", children:[
{
value: "1-1-2-1",
children: [
{ value: "1-1-2-1-1" },
{ value: "1-1-2-1-2" }
]
},
{
value: "1-1-2-2"
}
] }
]
},
{
value: "1-2",
children: [
{ value: "1-2-1"},
{ value: "1-2-2", children:[
{
value: "1-2-2-1",
children: [
{ value: "1-2-2-1-1" },
{ value: "1-2-2-1-2" }
]
},
{
value: "1-2-2-2"
}
] }
]
},
];
how should such a tree search be completed?
2018-06-26 Update
I wrote a version of DFS by myself last night. It doesn"t seem to work very well, but it works
.const search = (nodes, keyword) => {
let newNodes = [];
for (let n of nodes) {
if (n.children) {
const nextNodes = this.keywordFilter(n.children, keyword);
if (nextNodes.length > 0) {
n.children = nextNodes;
} else if (n.label.toLowerCase().includes(keyword.toLowerCase())) {
n.children = nextNodes.length > 0 ? nextNodes : [];
}
if (
nextNodes.length > 0 ||
n.label.toLowerCase().includes(keyword.toLowerCase())
) {
newNodes.push(n);
}
} else {
if (n.label.toLowerCase().includes(keyword.toLowerCase())) {
newNodes.push(n);
}
}
}
return newNodes;
};