【JS】数组扁平化
递归和非递归版本
const arr = [
123,
2,
[
2,3,4
,[
345,
34,
[
34,34,34
]
]
]
]
const flatten = (arr) => {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
console.log(flatten(arr));
const flatten2 = (arr) => {
const stack = [...arr]
console.log('stack = ', stack)
const res = []
while(stack.length) {
const item = stack.pop()
console.log('item = ', item)
if(Array.isArray(item)) {
stack.push(...item)
}
else {
res.unshift(item)
}
}
return res
}
console.log(flatten2(arr));