扁平化多维数组,分别用es6和es10方法处理

Posted on 2020-10-01 23:29  猫头唔食鱼  阅读(409)  评论(0编辑  收藏  举报

把多维数组转化为一维数组

es6写法

const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
        console.log(deepFlatten([1, [2], [[3], 4], 5,[6,[7,8],[[9,10],11,12],13,[14]]])); // [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
        console.log(deepFlatten([[1,2,3],[2,4,6]]))  // [1,2,3,4,5,6]

es10语法:flat(n)

 // 用es10的flat 方法
       console.log( [1, [2], [[3], 4], 5,[6,[7,8],[[9,10],11,12],13,[14]]].flat(4));  // [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
       console.log(  [[1,2,3],[2,4,6]].flat(4)); // [1,2,3,4,5,6]