数组扁平化是指将一个多维数组变为一个一维数组
- reduce
const arr = [1, [2, [3, [4, 5]]], 6]
// => [1, 2, 3, 4, 5, 6]
// reduce
const flatten = list => {
console.log(list)
return list.reduce((pre, curr) => {
console.log(pre, curr)
return pre.concat(isArray(curr) ? flatten(curr) : curr)
}, [])
}
console.log(flatten(arr))
- 递归
// 递归
const res = []
const flatten = list => {
for (let index = 0; index < list.length; index++) {
const element = list[index]
if (isArray(element)) {
flatten(element)
} else {
res.push(element)
}
}
}
flatten(arr)
console.log(res)