Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

几行代码解决树结构平铺 #66

Open
lizhongzhen11 opened this issue Nov 11, 2019 · 0 comments
Open

几行代码解决树结构平铺 #66

lizhongzhen11 opened this issue Nov 11, 2019 · 0 comments

Comments

@lizhongzhen11
Copy link
Owner

lizhongzhen11 commented Nov 11, 2019

先说结果代码:

const flatTree = (arr) => {
  return arr.reduce((item, next) => {
    return next.children ? item.concat(flat(next.children), next) : item.concat(next)
  }, [])
}

测试数据:

const city = [
  {
    value: '11',
    children: [
      {
        value: '11',
        children: [
          {
            value: '1100'
          }
        ]
      }
    ]
  },
  {
    value: '12',
    children: [
      {
        value: '120',
        children: [
          {
            value: '1200'
          }
        ]
      }
    ]
  },
  {
    value: '22',
    children: [
      {value: '220'},
      {value: '221', children: [{value: '2210'}]}
    ]
  }
]

项目需要,我一般这样去平铺树结构的:

let result = [];
const flat = (arr) => {
  arr.forEach(item => {
    result.push(item);
    item.children && flat(item.children);
  })
}
flat(目标树数据);
// 然后得到平铺后的result

很low有没有?
但是抱歉,我一直都这样玩的。。。

直到上周看到前端群里有人只用了大概一两行代码就实现我这么多行代码的功能,我当时就震惊了。虽然当时比较闲,但是处于划水状态,我也认真看了,以为我理解了,直到今天下午用到时,我才发现我根本不会!!!

我下午想了两小时,一直错以为内部用map,就这样陷入死境,根本想不通。我下午这样想的:

const flat = (arr) => {
  return arr.map(item => {
    return item.children ? flat(item.children).concat(item) : item;
  })
}

打印测试才发现,一点变化都没有!!!我一直都在纠结怎么让flat(item.children)执行的结果数据平铺到父级数组中,我到处加...,不是报错就是没用。

就在刚刚,跟朋友聊到,他说flat可不可以,我当时就否了,毕竟内部是树结构对象,flat在内部元素是基本类型才行,不过,我还是去MDN上看了下,结果,卧槽,多亏了朋友阳阳,我看到有个 reduce+concat 模拟实现flat功能的方法,卧槽,我的回忆也立马出现,就是 reduce+concat !!!

然后我开始尝试着去写,发现对reduce还是不熟,说到底写不出来就是不理解,不熟练!!!

丢人!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant