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

实现flat函数 #12

Open
sihai00 opened this issue Jul 26, 2019 · 0 comments
Open

实现flat函数 #12

sihai00 opened this issue Jul 26, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 26, 2019

实现flat函数

flat函数就是扁平化嵌套数组,例如:

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
 // [1, 2, 3, 4]

1. Array.prototype.flat

function flat(arr){
  return arr.flat(Infinity)
}
flat([1, [2, [3, [4, [5]]]]])
// [1, 2, 3, 4, 5]

2. 字符串化

[1, [2, [3, [4, [5]]]]].toString().split(',').map(v => +v) 
// [1, 2, 3, 4, 5]

3.concat和reduce递归

function flat(arr){
  return arr.reduce((pre, next) => pre.concat(Array.isArray(next) ? flat(next) : [next]), [])
}
flat([1, [2, [3, [4, [5]]]]]) 
// [1, 2, 3, 4, 5]

4.循环判断

function flat(arr){
  if (!Array.isArray(arr)) return arr
  var res = []
  var stack = [...arr]
  while(stack.length) {
    var next = stack.shift()
    if (Array.isArray(next)) {
      stack.push(...next)
    } else {
      res.push(next)
    }
  }
  return res
}
flat([1, [2, [3, [4, [5]]]]])
@sihai00 sihai00 self-assigned this Jul 26, 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