JS数组中的方法 flat(),flatMap()

本文介绍了JavaScript中的数组方法flat和flatMap。flat方法用于数组降维,将嵌套数组展开为一维数组;flatMap则先应用映射函数,然后将结果扁平化为一个新数组。示例展示了如何使用这两个方法处理嵌套数据和对象数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、flat()

官方解释:该方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
口水话解释:数组降维操作

语法

var newArray = arr.flat([depth])

参数:

depth 可选
指定要提取嵌套数组的结构深度(降维深度),默认值为 1。

例子
1.扁平化嵌套数组
  
   const newArr = [1, 2, 3, ['a', 'b', 'c', ['Aa']]].flat(2)//[1,2,3,"a","b","c","Aa]
   const newArr2 = [1, 2, 3, ['a', 'b', 'c', ['Aa']]].flat(2)//[1, 2, 3, ['a', 'b', 'c', ['Aa']]].flat(1) 
2.Infinity扁平化任意深度
  const newArr2 = [1, 2, 3, ['a', 'b', 'c', ['Aa']]].flat(Infinity)//[1, 2, 3, ['a', 'b', 'c', ['Aa']]].flat(1) 
3.扁平化与空项
 const newArr = [1, 2, 3, , 6, 8].flat() // [1, 2, 3, 6, 8]

二、flatMap()

官方解释:flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。
口水话:xxx

语法

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// 返回新数组的元素
}[, thisArg])

参数
callback

可以生成一个新数组中的元素的函数,可以传入三个参数:

currentValue

当前正在数组中处理的元素

index可选

可选的。数组中正在处理的当前元素的索引。

array可选

可选的。被调用的 map 数组

thisArg可选

可选的。执行 callback 函数时 使用的this 值。
返回值
一个新的数组,其中每个元素都是回调函数的结果,并且结构深度 depth 值为1。

描述

有关回调函数的详细描述,请参见 Array.prototype.map() 。 flatMap 方法与 map 方法和深度depth为1的 flat 几乎相同.

示例

Map 与 flatMap
const arr1 = [1, 2, 3, 4]
const arr2 = arr1.map(x => [x * 2])
// [[2], [4], [6], [8]]

const arr3 = arr1.flatMap(x => [x * 2])
// [2, 4, 6, 8]

// 只会将 flatMap 中的函数返回的数组 “压平” 一层
const arr4=arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

扁平化实际运用

  const data = [
    {
      code: 1001,
      name: 'zs',
      age: 12,
      address: '重庆',
      mark: '',
      sourceCodeList: [
        { checked: false, num: 0, mark: '主导打包' },
        { checked: true, num: 1, mark: '333' }
      ]
    },
    {
      code: 1002,
      name: 'ls',
      age: 15,
      address: '武汉',
      sourceCodeList: [
        { checked: false, num: null, mark: '1111' },
        { checked: true, num: 1, mark: '111' }
      ]
    },
    {
      code: 1003,
      name: 'ww',
      age: 15,
      address: '深圳',
      sourceCodeList: [{ checked: false, num: 11, mark: '' }]
    }
  ]
  

  const stockRegisterDetailList2 = data.flatMap(
    ({ sourceCodeList, ...parent }) =>
      sourceCodeList.map(child => ({ ...parent, ...child }))
  )
  const stockRegisterDetailList3 = data
    .map(({ sourceCodeList, ...parent }) =>
      sourceCodeList.map(child => ({ ...parent, ...child }))
    )
    .flat()
  console.log(stockRegisterDetailList2)
  console.log(stockRegisterDetailList3)
03-21
### Flat in Programming or Data Structures In the context of programming and data structures, **flat** refers to transforming nested or hierarchical data into a single-level representation. This concept is often applied when dealing with structured or semi-structured data[^1]. For instance, structured data typically follows a well-defined schema and can be represented in tables with rows and columns as mentioned earlier. When discussing flat operations within programming: - A **flattened array** involves converting multi-dimensional arrays (such as two-dimensional or three-dimensional arrays) into one-dimensional arrays. Here’s an example demonstrating how a multidimensional array might be flattened using Python: ```python def flatten_array(nested_list): result = [] for element in nested_list: if isinstance(element, list): result.extend(flatten_array(element)) else: result.append(element) return result nested_data = [[1, 2], [3, [4, 5]], [6]] print(flatten_array(nested_data)) # Output: [1, 2, 3, 4, 5, 6] ``` Additionally, flattening may also apply to objects or dictionaries where deeply nested key-value pairs are transformed into a simpler format. For databases, particularly NoSQL ones that handle semi-structured data like JSON documents, flattening could mean restructuring these complex hierarchies so they fit better into relational models or simplify querying processes without losing essential information about relationships between entities. Thus, while not explicitly stated under categories such as 'structured', understanding what makes certain types more amenable towards being made "flat" depends heavily on their inherent organization before transformation occurs—whether it's through code logic during runtime execution phases involving lists/arrays etc., database design considerations around indexing mechanisms over large datasets containing varied levels depth depending upon use case requirements at hand!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值