DamomHd / interview-question

整理各大厂面试题
1 stars 0 forks source link

实现数组扁平化 #15

Open DamomHd opened 3 years ago

DamomHd commented 3 years ago

多维数组=》一维数组

let arr = [1, [2, [3, [4, [5, ] , 6], 7], 8]]
let str = JSON.stringify(arr)
DamomHd commented 3 years ago

ES6的flat方法

arr = arr.flat(Infinity)
DamomHd commented 3 years ago

replace + split

arr = str.replace(/(\[|\])/g,'').split(',')
DamomHd commented 3 years ago

replace + JSON.parse

str = str.replace(/(\[|/])/g,'')
str = '[' + str + ']'
arr = JSON.parse(str)
DamomHd commented 3 years ago

常规递归

let result = []
function myFlat(arr){

    for(let i = 0;i<arr.length;i++){
        let item = arr[i]
        if(Array.isArray(item)) {
            myFlat(item)
        }
        else{
            result.push(item)
        }
    }
    return result
}
DamomHd commented 3 years ago

常规递归进阶版

function myFlat(arr){
  return arr.reduce((pre,cur)=>{
    return pre.concat(Array.isArray(cur) ? myFlat(cur) : cur)
  }, [])
}
DamomHd commented 3 years ago

ES6扩展运算符

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