数组扁平化(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

  • MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
arr.flat(Infinity); 

2. Array.reduce

  • MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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();
 }

参考文档

  • https://www.cnblogs.com/wind-lanyan/p/9044130.html
  • https://juejin.cn/post/6875152247714480136

你可能感兴趣的:(数组扁平化(flatten))