serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

数组扁平化 #4

Open serendipityApe opened 3 years ago

serendipityApe commented 3 years ago

题目 implement Array.prototype.flat()

写一个函数实现Array.prototype.falt。

例子

const arr = [1, [2], [3, [4]]];

flat(arr)
// [1, 2, 3, [4]]

flat(arr, 1)
// [1, 2, 3, [4]]

flat(arr, 2)
// [1, 2, 3, 4]

答案


//递归
function flat(arr,depth=1){
return depth ? arr.reduce((acc,item) => {
return [...acc,...(Array.isArray(item) ? flat(item,depth-1) : [item])]
},[])
: arr
}

//非递归 function flat(arr,depth=1){ let res=[]; let stock=arr.map((item) => [item,depth]); while(stock.length){ let [top,depth]=stock.pop(); if(depth && Array.isArray(top)){ stock.push(...top.map((item) => [item,depth-1])) }else{ res.push(top); } } return res.reverse(); }

//尝试半天用正则表达式写,但好像并不可行