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

把一个多维数组拍平成一维数组 #39

Open
bibi7 opened this issue Oct 28, 2019 · 1 comment
Open

把一个多维数组拍平成一维数组 #39

bibi7 opened this issue Oct 28, 2019 · 1 comment

Comments

@bibi7
Copy link
Owner

bibi7 commented Oct 28, 2019

话不多说。

const array = [1, 2, 3, [4, 5], [6, 7, 8, [9, 10]]]

const flatArray = (array, temp = []) => {
  array.map(item => {
    if (Array.isArray(item)) {
      flatArray(item, temp)
    } else {
      temp.push(item)
    }
  })
  
  return temp
}

增加一点边际条件:

const flatArray = (array, temp = []) => {
  if (!Array.isArray(array)) {
    throw new Error(`尝试打平的数据为${typeof array},请输入一个数组。`)
    return
  }

  array.map(item => {
    if (Array.isArray(item)) {
      flatArray(item, temp)
    } else {
      temp.push(item)
    }
  })

  return temp
}

玩点高级的简写?

const flatArray = array => array.reduce((acc, cur) => Array.isArray(cur) ? [...acc, ...flatArray(cur)] : [...acc, cur], [])

不考虑递归的话,采用以下迭代的想法试试

//其实我还是比较喜欢reduce的递归方式,优雅得多?
const flatArray = (array, temp = []) => {
  const newArray = [...array]
  while (newArray.length) {
    const item = newArray.shift()
    if (Array.isArray(item)) {
      newArray.unshift(...item)
    } else {
      temp.push(item)
    }
  }
  return temp
}
@bibi7
Copy link
Owner Author

bibi7 commented Oct 29, 2019

传送门

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