You need to enable JavaScript to run this app. JavaScript实现固定长度结构化数组转换为层级树的高效方案
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 01:54:03