数组扁平化(flatten)

数组扁平化:
输入:const data = [ 1,2 ,[3,4,6,8],[1,2,[2]]];
输出:[1,2,3,4,6,8,1,2,2]

方法总结

  1. 数组自带的flat
  2. 递归
  • reduce ,concat结合做递归
  • 循环递归
  1. 扩展运算符
  2. 利用字符串
  3. 通过json
  4. 栈加扩展运算符

1. Array.prototype.flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth

arr.flat(Infinity); 

2. Array.reduce

const flatten = function( arr ){
   return  arr.reduce(( prev,cur)=>{
        return prev.concat( Array.isArray(cur) ? flatten( cur) : cur );
    },[])
}

3. 扩展运算符

const flatten1 = function( arr ){
    while( arr.some( item => Array.isArray(item))){
        arr = [].concat(...arr)
    }
    return arr;
}

4. 递归

function flatten(arr) {
    var res = [];
    arr.map(item => {
        if(Array.isArray(item)) {
            res = res.concat(flatten(item));
        } else {
            res.push(item);
        }
    });
    return res;
}

5. toString ,split

const flatten = function( arr ){
    return arr.toString().spilt(',').map( item=>{
        return item
    })
}

6. join ,split

const flatten = function( arr ){
    return arr.join(',').split(',').map( item=>{
        return item
    })
}

7. 正则

数据类型都会变为字符串,如需要,map做解析

const res = JSON.stringify(arr).replace(/\[|\]/g, '').split(',');

8. 正则二

const res = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');

9. 栈

const flatten = function( arr ){
    const stack = [...arr];
    let res = [];
    while ( stack.length ) {
        const next = stack.pop();
        if( Array.isArray(next) ){
            stack.push(...next);
        }else{
            res.push(next);
        }
    }
    return res.reverse();
 }

参考文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容