flat
将嵌套数组扁平化。
语法
typescript
flat<T>(
array: T[],
depth?: number
): T[]
参数
array
(T[]): 要扁平化的数组depth
(number, 可选): 扁平化的深度,默认为 1
返回值
T[]
: 扁平化后的数组
示例
基本用法
typescript
import { flat } from 'radash'
const nested = [1, [2, 3], [4, [5, 6]]]
const flattened = flat(nested)
// [1, 2, 3, 4, [5, 6]]
指定深度
typescript
import { flat } from 'radash'
const deeplyNested = [1, [2, [3, [4, 5]]]]
const flattened = flat(deeplyNested, 2)
// [1, 2, 3, [4, 5]]
完全扁平化
typescript
import { flat } from 'radash'
const deeplyNested = [1, [2, [3, [4, 5]]]]
const completelyFlattened = flat(deeplyNested, Infinity)
// [1, 2, 3, 4, 5]
处理对象数组
typescript
import { flat } from 'radash'
const users = [
[
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
],
[
{ name: 'Charlie', age: 35 }
]
]
const flattenedUsers = flat(users)
// [
// { name: 'Alice', age: 25 },
// { name: 'Bob', age: 30 },
// { name: 'Charlie', age: 35 }
// ]
处理混合类型
typescript
import { flat } from 'radash'
const mixed = [
'a',
[1, 2],
{ name: 'test' },
[true, false]
]
const flattened = flat(mixed)
// ['a', 1, 2, { name: 'test' }, true, false]
处理空数组
typescript
import { flat } from 'radash'
const arrays = [
[1, 2],
[],
[3, 4],
[]
]
const flattened = flat(arrays)
// [1, 2, 3, 4]
处理字符串数组
typescript
import { flat } from 'radash'
const words = [
['hello', 'world'],
['goodbye', 'moon'],
['hello', 'sun']
]
const allWords = flat(words)
// ['hello', 'world', 'goodbye', 'moon', 'hello', 'sun']
处理数字数组
typescript
import { flat } from 'radash'
const numbers = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
const allNumbers = flat(numbers)
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
处理空值
typescript
import { flat } from 'radash'
const withNulls = [
[1, null, 3],
[null, 5, 6],
[7, 8, null]
]
const flattened = flat(withNulls)
// [1, null, 3, null, 5, 6, 7, 8, null]
注意事项
- 深度参数: 如果不指定深度,默认为 1
- 性能: 时间复杂度取决于数组的嵌套深度
- 空值: 保留 null 和 undefined 值
- 非数组元素: 非数组元素会被保留
与其他函数的区别
flat
: 扁平化嵌套数组flatten
: 类似功能,但可能有不同的实现flattenDeep
: 完全扁平化
性能
- 时间复杂度: O(n × d),其中 n 是元素总数,d 是深度
- 空间复杂度: O(n)
- 适用场景: 数据处理和数组操作