1.
function flat(arr) {
// 验证 arr 中,还有没有深层数组 [1, 2, [3, 4]]
const isDeep = arr.some(item => item instanceof Array)
if (!isDeep) {
return arr // 已经是 flatern [1, 2, 3, 4]
}
const res = Array.prototype.concat.apply([], arr)
return flat(res) // 递归
}
const res = flat( [1, 2, [3, 4, [10, 20, [100, 200]]], 5] )
console.log(res)
2.
let a = [[1,2], [6, [3, 4, 5]]]
let b = [0, 10, [11, 12, [13, 14], 15]]
flatten = arr => {
let newArr = []
arr.reduce((per, cur) => {
newArr = Array.isArray(cur) ? newArr.concat(flatten(cur)) : newArr.concat(cur)
}, [])
return newArr
}
flatten扁平化数组实现
最新推荐文章于 2022-10-31 18:05:08 发布