蔚来 - 前端日常一面
贡献一篇 经典的树形类题目 - 搜索树状关键词
好久前面蔚来 还是了理想时出的
// 实现一个函数search可以进行关键词搜索,返回出关键词出现的链路 // 比如 search('西半') 返回 ['北京市', '朝阳区', '西半街道'] // 比如 search('朝阳区') 返回 ['北京市', '朝阳区'] // 比如 search('街道') 返回 ['北京市', '昌平区', '昌平街道']、 ['北京市', '朝阳区', '西半街道'] let testObj = { babel: '北京市', child: [ { babel: '朝阳区', child: [ { babel: '西半街道', }, { babel: '向上向善', } ] }, { babel: '昌平区', child: [ { babel: '香水百合', }, { babel: '昌平街道', } ] } ] }
自己写的复盘 -
let testObj = { babel: '北京市', child: [ { babel: '朝阳区', child: [ { babel: '西半街道', }, { babel: '向上向善', } ] }, { babel: '昌平区', child: [ { babel: '北香水百合', }, { babel: '昌平街道', } ] } ] }; function search(keyword, node = testObj, path = []) { const newPath = [...path, node.babel]; let results = []; if (node.babel.includes(keyword)) {//includes就可以部分匹配(当时不会部分匹配) results.push(newPath); } if (node.child) { for (const child of node.child) { results = results.concat(search(keyword, child, newPath)); // 合并数据 } } return results; } // 测试示例 console.log(search('西半')); // [ [ '北京市', '朝阳区', '西半街道' ] ] console.log(search('朝阳区')); // [ [ '北京市', '朝阳区' ] ] console.log(search('街道')); // [ [ '北京市', '朝阳区', '西半街道' ], [ '北京市', '昌平区', '昌平街道' ] ] console.log(search('北')); // [ [ '北京市' ], [ '北京市', '昌平区', '北香水百合' ] ]