flatArray - 数组扁平化

66 阅读1分钟

代码实现

/**
* @description: flatArray
* @author: huen2015
*/
// level < 0 => 深层扁平化
function flatArray(arr: any[], level: number = 0): any[] {
    let result: any[] = []

    arr.forEach((item: any) => {
        if (level !== 0 && Array.isArray(item)) {
            // 扁平 1 层
            result = result.concat(flatArray(item, level - 1))
        } else {
            result = result.concat([item])
        }
    })

    return result
}

const flatArrayData = [1, 2, 3, [[4, 5], 6], 7, 8]
const flatArrayResult0 = flatArray(flatArrayData, 0)
const flatArrayResult1 = flatArray(flatArrayData, 1)
const flatArrayResult2 = flatArray(flatArrayData, 2)
const flatArrayResult3 = flatArray(flatArrayData)
const flatArrayResult4 = flatArray(flatArrayData, -100)
console.log('flatArrayResult0', flatArrayResult0) // [1, 2, 3, [[4, 5], 6], 7, 8]
console.log('flatArrayResult1', flatArrayResult1) // [1, 2, 3, [[4, 5], 6, 7, 8]
console.log('flatArrayResult2', flatArrayResult2) // [1, 2, 3, 4, 5, 6, 7, 8]
console.log('flatArrayResult3', flatArrayResult3) // [1, 2, 3, [[4, 5], 6], 7, 8]
console.log('flatArrayResult4', flatArrayResult4) // [1, 2, 3, 4, 5, 6, 7, 8]

代码演示仓库