let arr = [1, [2, 3, [4, 5]]]
function flat1(arr) {
let arrs = []
while(arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr)
}
console.log(arr)
}
function flat2(arr) {
const arrs = []
while(arr.length) {
const a = arr.shift();
if (Array.isArray(a)) {
arr.unshift(...a)
} else {
arrs.push(a)
}
}
console.log(arrs)
}
function flat3(arr) {
let arrs = [];
arr.forEach(item => {
if (Array.isArray(item)) {
arrs.push(...flat3(item))
} else {
arrs.push(item)
}
})
return arrs
}
function flat4(arr) {
return arr.reduce((acc, cur) => {
if (Array.isArray(cur)) {
return [...acc, ...flat4(cur)]
} else {
return [...acc, cur]
}
}, [])
}
// flat1(arr)
// flat2(arr)
console.log(flat3(arr))
// console.log(flat4(arr))
console