JavaScript之数组扁平化

前言

所谓的数组扁平化指将多维度的数组转换为以为数组。

正文

        //数组扁平化处理
        function test(arr) {
            let result = []
            for (let item of arr) {
                if (Array.isArray(item)) {
                    result = result.concat(test(item))
                } else {
                    result.push(item)
                }
            }
            return result
        }
        function test (arr) {
            return arr.reduce((pre, next) => {
                return pre.concat(Array.isArray(next) ? test(next) : next)
            }, [])
        }
        let array = [1, ['1', '2', 3, [1, 4, '5', 4, '7']],
            ['1', '2', 3, 4, 5, ['1', 2, '5']]
        ]
        console.log(test(array))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容