es6之数组的flat(),flatMap()

数组的成员有时还是数组,Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维数组。该方法返回一个新数组,对原数据没有影响。

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]

上面代码中,原数组的成员里面有一个数组,flat()方法将子数组的成员取出来,添加在原来的位置。

flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1。

[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

上面代码中,flat()的参数为2,表示要拉平两层的嵌套数组。

如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。

[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

如果原数组有空位,flat()方法会跳过空位。

[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]

flatMap()方法对原数组的每个成员执行一个函数,相当于执行Array.prototype.map(),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

flatMap()只能展开一层数组。

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!
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值