JavaScript实现固定长度结构化数组转换为层级树的高效方案
结构化数组转层级树形结构JavaScript实现方案
实现思路
- 过滤每条数组项的null值,得到无间隙的有效层级路径
- 从根层级开始逐层匹配路径节点,已存在同标签节点则复用,不存在则新建
- 全部路径处理完成后清理所有空children属性,匹配目标输出格式要求
实现代码
// 辅助函数:删除节点的空children属性 function removeEmptyChildren(node) { if (node.children?.length === 0) { delete node.children; } else if (node.children) { node.children.forEach(removeEmptyChildren); } return node; } function buildTree(flatArray) { const result = []; // 遍历所有扁平结构项 flatArray.forEach(row => { const validPath = row.filter(item => item !== null); let currentLevel = result; // 逐层处理路径节点 validPath.forEach(label => { const existNode = currentLevel.find(item => item.label === label); if (!existNode) { const newNode = { label }; currentLevel.push(newNode); currentLevel = newNode.children = []; } else { existNode.children = existNode.children || []; currentLevel = existNode.children; } }) }) // 清理空children后返回最终结果 return result.map(removeEmptyChildren); }
使用示例
// 题目给出的输入数据 var geographies = [ [ 'Denmark', 'Midtjylland', null, null, null ], [ 'Denmark', 'Syddanmark', 'Langeland', null, null ], [ 'Denmark', 'Syddanmark', 'Ærø', null, null ], [ 'Japan', 'Okinawa', 'Izenajima', null, null ], [ 'Japan', 'Hokkaido', 'Rishiri', 'Rishiri-to', null ] ] // 调用方法得到目标树形结构 const outputTree = buildTree(geographies);
方案特点
时间复杂度为O(n*k),其中n为输入数组长度,k为单条路径的最大层级(本题固定为5),执行效率极高,完全适配题目给出的「无空值间隙、数组项长度固定」的前置约束,输出结果与要求格式完全一致。
内容的提问来源于stack exchange,提问作者Timothy Dalton
相关产品推荐
相关产品推荐

