js中数组flat方法的使用和实现


定义

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

语法

var newArray = arr.flat([depth])

参数

depth:可选参数,指定提取的嵌套数组的深度,默认值为1

返回值

一个包含将数组与子数组中所有元素的新数组。(就是扁平化后的每一项重新组成的数组,所以不会改变原数组。)

示例

const arr5 = [1,2,[3,[4,5]], [6,[7]], 8]
function getFlatArr (list) {
  return list.reduce((pre, item) => {
    return pre.concat(item)
  }, [])
}
console.log(getFlatArr(arr5))
// [1,2,3,[4,5],6,[7],8]

方法实现

通过reduce实现

function getFlatArr(arr, depth) {
   return depth > 0 ? arr.reduce((pre, item) => {
     return pre.concat(Array.isArray(item) ?  getFlatArr(item, depth - 1): item)
}, []) : arr.slice();
}

forEach + 递归实现

function getFlatArr(list, depth = 1) {
  const result = [];
  (function flat(list, depth) {
    list.forEach((ele) => {
      if(Array.isArray(ele) && depth > 0 ) flat(ele, depth -1) else result.push(ele)
    })
  })(list, depth)
}

Leave a Reply

Your email address will not be published. Required fields are marked *