題目:實現一個對樹型結構進行過濾的函數,其中樹形結構的格式如下: tree = [ {name: ‘A’}, {name: ‘B’,
children: [ {name: ‘A’}, {name: ‘AA’, children: […]} ]}, {name: ‘C’}
]
假設我輸入的 str 爲 A 則過濾後返回的結果爲 [ {name: ‘A’}, {name: ‘B’, children: [ {name: ‘A’} ]} ]
假設我輸入的 str 爲 AA 則過濾後返回的結果爲 [ {name: ‘B’, children: [ {name: ‘AA’, children: […]} ]} ]
假設我輸入的 str 爲 B 則過濾後返回的結果爲 [ {name: ‘B’, children: [ {name: ‘A’}, {name: ‘AA’, children: […]} ]} ]
// 實現該函數,要求不允許對原有的tree做任何修改,最終返回結果是一棵新結構出來的樹 function filter (tree, str) {}
const tree = [
{ name: "A" },
{ name: "B", children: [{ name: "A" }] },
{
name: "AA",
children: [
{ name: "BB" },
{ name: "C" },
{ name: "D", children: [{ name: "A" }] },
{ name: "A" },
],
},
{ name: "D", children: [{ name: "C", children: [{ name: "AA" }] }] },
];
function clear(tree, str) {
if (!tree) return [];//處理葉節點
let result = [];
tree.map((item) => {
let it = { ...item }; //每項淺拷貝一下保證不影響原來的tree
if (it.name === str) {
result.push(it);
} else {
let obj = clear(it.children, str);
//得到children的返回的result數組,放到拷貝對象的children中
if (obj.length > 0) {
it.children = obj;
result.push(it);
}
}
});
return result;//每層返回一個數組
}
console.log(clear(tree, "A"));
console.log(tree);