手写一个JS函数,实现数组扁平化Array Flatten

写一个函数,实现 Array flatten 扁平化,只减少一个嵌套层级

例如输入 `[1, 2, [3, 4, [100, 200], 5], 6]` 返回 `[1, 2, 3, 4, [100, 200], 5, 6]`

思路

定义空数组 arr = [],遍历当前数组

如果 item 非数组,则累加到 arr

如果 item 是数组,则遍历之后累加到 arr

/**
 * @description 数组扁平化
 */

/**
 * 数组扁平化,使用 push
 * @param arr arr
 */
export function flatten1(arr: any[]): any[] {
    const res: any[] = []

    arr.forEach(item => {
        if (Array.isArray(item)) {
            item.forEach(n => res.push(n))
        } else {
            res.push(item)
        }
    })

    return res
}

/**
 * 数组扁平化,使用 concat
 * @param arr arr
 */
export function flatten2(arr: any[]): any[] {
    let res: any[] = []

    arr.forEach(item => {
        res = res.concat(item)
    })

    return res
}

// // 功能测试
// const arr = [1, [2, [3], 4], 5]
// console.info( flatten2(arr) )

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124945861