【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));

 

posted @ 2023-09-10 21:53  zjy4fun  阅读(4)  评论(0编辑  收藏  举报