前端面试之数组打平

let arr = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];

flatten1 = arr => arr.flat(Infinity)

flatten2 = arr => arr.toString().split(',').map(item => Number(item))


flatten3 = arr => {
    while (arr.some(Array.isArray)) {
        arr = [].concat(...arr);
    }
    return arr
}

flatten4 = arr => {
    return arr.reduce((result, item) => {
        return result.concat(Array.isArray(item) ? flatten4(item) : item)
    }, [])
}

 

你可能感兴趣的:(前端面试之数组打平)