数组扁平化 flat 实现

1,619 阅读1分钟

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

语法

var newArray = arr.flat([depth])
  • 参数

    depth 可选

    指定要提取嵌套数组的结构深度,默认值为 1

  • 返回值

    一个包含将数组与子数组中所有元素的新数组。

示例

const nested = [ ['📦', '📦'], ['📦']]

const flattened = nested.flat()

console.log(flattened)
// ['📦', '📦', '📦']

flat()方法设置 depth 参数:

const twoLevelsDeep = [[1, [2, 2], 1]];

// depth = 1
twoLevelsDeep.flat()
// [1, [2, 2], 1]

// depth = 2
twoLevelsDeep.flat(2)
// [1, 2, 2, 1]

flat()方法设置 depth 参数为 Infinity

const veryDeep = [[1, [2, 2, [3,[4,[5,[6]]]]], 1]];

veryDeep.flat(Infinity);
// [1, 2, 2, 3, 4, 5, 6, 1]

flat() 方法会移除数组中的空项

const missingNumbers = [1, ,3, ,5];

missingNumbers.flat();
// [1, 3, 5];

polyfill

  • reduce + concat +isArray +recursivity

    Array.prototype.flat = function (depth = 1) {
      return depth > 0 ? this.reduce(
        (prev, next) => prev.concat(Array.isArray(next) ? next.flat(depth - 1) : next)
        , [])
        : this
    } 
    
  • map + concat +spread + isArray + recursivity

Array.prototype.flat = function(depth = 1){
  return depth > 0 ? [].concat(...this.map(v => Array.isArray(v) ? v.flat(depth - 1) : v))
  : this
}