weijiyang / GOOD-IDEA

这里记录一些灵感~详见ISSUES
1 stars 0 forks source link

分别用迭代 递归的方式 实现flatten函数 #57

Open weijiyang opened 4 years ago

weijiyang commented 4 years ago

迭代

function flatten (arr) {
  while(arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr)
  }
 return arr
}

递归

function flatten (arr) {
  return arr.reduce((_arr, cur)=>{
    if(Array.isArray(cur)){
      _arr = _arr.concat(...flatten(cur))
    } else {
     _arr.push(cur)
   }
  },[])
}

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