JS中flat---数组扁平化

需求:多维数组=>一维数组

let ary = [1, [2, [3, [4, 5]]], 6];// -> [1, 2, 3, 4, 5, 6]
let str = JSON.stringify(ary);

  

1. 调用ES6中的flat方法

ary = ary.flat(Infinity);

  

2. replace + split

ary = str.replace(/(\[|\])/g, '').split(',')

  

3. replace + JSON.parse

str = str.replace(/(\[|\])/g, '');
str = '[' + str + ']';
ary = JSON.parse(str);

  

4. 普通递归

let result = [];
let fn = function(ary) {
  for(let i = 0; i < ary.length; i++) {
    let item = ary[i];
    if (Array.isArray(ary[i])){
      fn(item);
    } else {
      result.push(item);
    }
  }
}

  

5. 利用reduce函数迭代

function flatten(ary) {
    return ary.reduce((pre, cur) => {
        return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
    }, []);
}
let ary = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(ary))

  

6:扩展运算符

//只要有一个元素有数组,那么循环继续
while (ary.some(Array.isArray)) {
  ary = [].concat(...ary);
}

  

 

posted @ 2020-01-15 15:13  zaijinyang  阅读(1744)  评论(0编辑  收藏  举报