数组的扁平化

数组的扁平化就是数组里面嵌套数组,最后需要的是只有一维的数据
1、es6提供的新方法flat(depth)

let a = [1,[2,3]];
a.flat(); // [1,2,3] 
a.flat(1); //[1,2,3]

flat(depth) 方法中的参数depth,代表展开嵌套数组的深度,默认是1

所以我们可以添加参数1,或者直接调用flat()来对2维数组进行扁平化,如果我们可以提前知道数组的维度,对这个数组进行扁平化处理,参数depth的值就是数组的维度减一。

let a = [1,[2,3,[4,[5]]]];
a.flat(4-1); // [1,2,3,4,5]  a是4维数组

其实还有一种更简单的办法,无需知道数组的维度,直接将目标数组变成1维数组。depth的值设置为Infinity。

let a = [1,[2,3,[4,[5]]]];
a.flat(Infinity); // [1,2,3,4,5]  a是4维数组

2、ES5+递归

var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]];
function flatten(arr) {
  var res = [];
  for(let i = 0, length = arr.length; i < length; i++) {
    if(Array.isArray(arr[i])) {
        res = res.concat(flatten(arr[i])); //concat 并不会改变原数组
        //res.push(...flatten(arr[i])); //扩展运算符
    } else{
        res.push(arr[i]);
    }
  }
  return res;
}
  flatten(arr1); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

3、ES6+reduce方法

var arr1 = [1, 2, [3], [1, 2, 3, [4, [2, 3, 4]]]];
function flatten(arr) {
  return arr.reduce((res,next) =>{
    return res.concat(Array.isArray(next)? flatten(next) : next);
  },[]);
 }

这里使用的是数组的reduce方法,需要注意的是reduce方法,我们传递了两个参数, 第一个参数就是就是处理扁平化的箭头函数 第二个参数是一个空数组,也是作为遍历的开始。(res)
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。
注:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
| total | 必需。初始值, 或者计算结束后的返回值。 |
| currentValue | 必需。当前元素 |
| currentIndex | 可选。当前元素的索引 |
| arr | 可选。当前元素所属的数组对象。 |

原文地址:https://www.cnblogs.com/axingya/p/14600448.html