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

数组扁平化 #21

Open
xxxgitone opened this issue Sep 21, 2017 · 0 comments
Open

数组扁平化 #21

xxxgitone opened this issue Sep 21, 2017 · 0 comments

Comments

@xxxgitone
Copy link
Owner

所谓数组扁平化,就是将内嵌数组转换成一层数组,这里有四种方式

// 递归
function flatten1 (arr) {
  let res = []
  
  arr.forEach((item) => {
    if (Array.isArray(item)) {
      res = res.concat(flatten1(item))
    } else {
      res.push(item)
    }
  })
  return res
}

// 当所有数组项都为数字的时候,可以使用toString()方法,
function flatten2 (arr) {
  return arr.toString().split(',').map((item) => {
    return +item
  })
}

// ...扩展运算符
function flatten3 (arr) {
  
  while (arr.some((item) => Array.isArray(item))) {
    arr = [].concat(...arr)
  }
  
  return arr
}

// reduce方法
function flatten4 (arr) {
  return arr.reduce((prev, next) => {
    return prev.concat(Array.isArray(next) ? flatten4(next) : next)
  }, [])
}

let arr = [1, 2, [3, [4, 5]]] // [1,2,3,4,5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant