手写flat,实现数组扁平化

254 阅读1分钟

flat的用法

js中使用flat方法可以扁平化数组

  • flat方法接收一个参数,表示需要扁平化的深度,默认为1
let a = [1, 2, [3, 4, [7, 8]], 5]
let b = a.flat()
console.log(b) // [1, 2, 3, 4, [7,8], 5]
  • 参数是Infinity(无穷)时,完全扁平化
    let a = [1, 2, [3, 4, [7, 8]], 5]
    let b = a.flat(Infinity)
    console.log(b) // [1, 2, 3, 4, 7, 8, 5]
  • 数组中为空的部分,扁平化后不保存,但undefined和null会保存
    let a = [1, 2, [3, 4, [7, 8,,,]], 5]
    let b = a.flat(Infinity)
    console.log(b) // [1, 2, 3, 4, 7, 8, 5]
    let a = [1, 2, [3, 4, [7, 8,undefined,null,]], 5]
    let b = a.flat(Infinity)
    console.log(b) // [1, 2, 3, 4, 7, 8, undefined, null, 5]

手写是实现数组扁平化

本文主要采用递归遍历的方式进行数组扁平化

  • 常规循环遍历数组
// 定义flat方法
Array.prototype.cusFlat = function (depth = 1) {
  const arr = this
  const resArr = []
  // 声明用于递归的函数
  const recursiveFn = function (resArr,dealArr, depth) {
    for (let item of dealArr) {
      // 深度不为0,且是数组,需要递归
      if (Array.isArray(item) && depth) {
        recursiveFn(resArr, item, depth - 1) // 递归
      } else {
        resArr.push(item)
      }
    }
  }
  // 执行处理数组
  recursiveFn(resArr,arr, depth)
  return resArr
}
// test
let a = [1, 2, [3, 4, [7, 8, undefined, null, [12, 9],]], 5]
console.log(a.cusFlat(Infinity)) // [1, 2, 3, 4, 7, 8, undefined, null, 12, 9, 5]
console.log(a.cusFlat())  // [1, 2, 3, 4,  [7, 8, undefined, null, [12, 9],], 5]
  • 使用reduce方法遍历
// 定义flat方法
Array.prototype.cusFlat = function (depth = 1) {
  const arr = this
  // 声明用于递归的函数
  const recursiveFn = function (dealArr, depth) {
    return dealArr.reduce((pre, item) => {
      // 深度不为0,且是数组,需要递归
      if (Array.isArray(item) && depth) {
        // 递归,并将结果合并,由于函数返回的是数组,所以需要展开
        pre.push(...recursiveFn(item, depth - 1)) 
      } else {
        pre.push(item)
      }
      return pre
    }, [])
  }
  // 执行处理函数
  return recursiveFn(arr, depth)
}
// test
let a = [1, 2, [3, 4, [7, 8, undefined, null, [12, 9],]], 5]
console.log(a.cusFlat(Infinity)) // [1, 2, 3, 4, 7, 8, undefined, null, 12, 9, 5]
console.log(a.cusFlat())  // [1, 2, 3, 4,  [7, 8, undefined, null, [12, 9],], 5]