前端面試題 數組 Flat 數組扁平化

數組扁平化: 用於將嵌套多層的數組「拉平」,變成一維的數組 一、[1, [2]] => [1,2]
二、[[1, 2], [3, 4]] => [1, 2, 3, 4]
三、[1, 2, [3, 4, [5, 6]]] => [1, 2, 3, 4, 5, 6]
複製代碼
方法一:

使用ES2019的 Array.prototype.flat 函數, 該函數接收一個number類型的參數,表示數組扁平化的深度。數組

let arr= [2, 3, 4, 5, [21, 22, 24, 25, [31, 33, 34, 35, [41]], 26], 9]
arr.flat(1)
// [2, 3, 4, 5, 21, 22, 24, 25, [31, 33, 34, 35, [41]], 26, 9]
arr.flat(2)
// [2, 3, 4, 5, 21, 22, 24, 25, 31, 33, 34, 35, [41], 26, 9]
arr.flat(4)
// [2, 3, 4, 5, 21, 22, 24, 25, 31, 33, 34, 35, 41, 26, 9]
複製代碼
方法二:

使用遞歸的方式來扁平化數組:bash

let flat: (arr: Array<any>) => Array<any> 
flat = function (arr: Array<any>): Array<any>{
  let newArr: Array<any> = []
  arr.map((val: any) => {
    if (Array.isArray(val)) {
      newArr = newArr.concat(flat(val))
    } else {
      newArr.push(val)
    }
  })
  return newArr
}

let arr= [2, 3, 4, 5, [21, 22, 24, 25, [31, 33, 34, 35, [41]], 26], 9]

flat(arr)
// [2, 3, 4, 5, 21, 22, 24, 25, 31, 33, 34, 35, 41, 26, 9]
複製代碼

該方法有一個缺點,就是數組嵌套層級過多時會拋出棧溢出的錯誤,那麼如何解決這個問題呢? 請看方法三。函數

方法二:

使用廣度優先(隊列)的方式來扁平化數組:ui

let flat: (arr: Array<any>) => Array<any>
flat = function (arr: Array<any>) {
  let newArr: Array<any> = []
  let queue: Array<any> = []
  queue.push(arr)
  while(queue.length) {
    let item = queue.shift()
    item.map((val) => {
      if (Array.isArray(val)) {
        queue.push(val)
      } else {
        newArr.push(val)
      }
    })
  }
  return newArr
}

let arr= [2, 3, 4, 5, [21, 22, 24, 25, [31, 33, 34, 35, [41]], 26], 9]

flat(arr)
// [2, 3, 4, 5, 21, 22, 24, 25, 31, 33, 34, 35, 41, 26, 9]
複製代碼

使用這種方法的話不管數組層級再深,也不會報錯。spa

相關文章
相關標籤/搜索