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

(javascript)数组扁平化 #24

Open
Zhengy1995 opened this issue Mar 17, 2020 · 0 comments
Open

(javascript)数组扁平化 #24

Zhengy1995 opened this issue Mar 17, 2020 · 0 comments

Comments

@Zhengy1995
Copy link
Owner

作用

其实,这个妹啥好说的,就是把多维数组降为一维,直接贴代码吧

  1. 实现方式一
const flatten = (arr = []) => {
  if(!Array.isArray(arr)) throw new Error('param is not Array, it cannot be flatten')
  const { length } = arr
  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) return flatten(arr.slice(0, i).concat(arr[i], arr.slice(i + 1)))
  }
  return arr
}
  1. 实现方式二
const flatten = (arr = [], result = []) => {
  if(!Array.isArray(arr)) throw new Error('param is not Array, it cannot be flatten')
  const { length } = arr
  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]))
      continue
    }
    result.push(arr[i])
  }
  return result
}

示例

const arr = [1, [2, [3, [4, [5, [6, [7]]]]]]]
console.log(flatten(arr)) // [1, 2, 3, 4, 5, 6, 7]

对于代码风格来讲,本人更倾向于第一种,但是性能来讲,第二种肯定更好~

原理

迭代+递归

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