用reduce 方法将树结构数组转为扁平数组

120 阅读1分钟
interface TreeNode {
  id: string;
  children?: TreeNode[];
}

const flattenTree = (tree: TreeNode[]): TreeNode[] => {
  return tree.reduce((result: TreeNode[], node: TreeNode) => {
    result.push(node);
    if (node.children) {
      result.push(...flattenTree(node.children));
    }
    return result;
  }, []);
};

这个函数接收一个树结构数组tree作为参数,返回一个扁平化后的数组。在函数内,使用Array.reduce方法和递归调用来将每个节点和其子节点转换为扁平数组中的一个元素。

Array.reduce方法的回调函数中,首先将当前节点node推入result数组。然后如果节点有子节点,就使用...展开运算符将子节点的扁平数组插入result数组中。 最后,返回result数组。

例如:

const tree: TreeNode[] = [
  {
    id: '1',
    children: [
      { id: '2' },
      { id: '3', children: [{ id: '4' }, { id: '5' }] },
      { id: '6' },
    ],
  },
  { id: '7' },
];

const flat = flattenTree(tree);
console.log(flat);
// Output: [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }, { id: '6' }, { id: '7' }]

树结构数组包含7个节点,其中3个节点有子节点。转换为扁平数组后,其中包含了所有的节点。