Skip to content

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. 深度參數: 如果不指定深度,默認為 1
  2. 性能: 時間復雜度取決於數組的嵌套深度
  3. 空值: 保留 null 和 undefined 值
  4. 非數組元素: 非數組元素會被保留

與其他函數的區別

  • flat: 扁平化嵌套數組
  • flatten: 類似功能,但可能有不同的實現
  • flattenDeep: 完全扁平化

性能

  • 時間復雜度: O(n × d),其中 n 是元素總數,d 是深度
  • 空間復雜度: O(n)
  • 適用場景: 數據處理和數組操作

Released under the MIT License.