Skip to content

flat

Flatten nested arrays.

Syntax

typescript
flat<T>(
  array: T[],
  depth?: number
): T[]

Parameters

  • array (T[]): The array to flatten
  • depth (number, optional): Flattening depth, defaults to 1

Return Value

  • T[]: Flattened array

Examples

Basic Usage

typescript
import { flat } from 'radash'

const nested = [1, [2, 3], [4, [5, 6]]]
const flattened = flat(nested)
// [1, 2, 3, 4, [5, 6]]

Specifying Depth

typescript
import { flat } from 'radash'

const deeplyNested = [1, [2, [3, [4, 5]]]]
const flattened = flat(deeplyNested, 2)
// [1, 2, 3, [4, 5]]

Complete Flattening

typescript
import { flat } from 'radash'

const deeplyNested = [1, [2, [3, [4, 5]]]]
const completelyFlattened = flat(deeplyNested, Infinity)
// [1, 2, 3, 4, 5]

Handling Object Arrays

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 }
// ]

Handling Mixed Types

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]

Handling Empty Arrays

typescript
import { flat } from 'radash'

const arrays = [
  [1, 2],
  [],
  [3, 4],
  []
]

const flattened = flat(arrays)
// [1, 2, 3, 4]

Handling String Arrays

typescript
import { flat } from 'radash'

const words = [
  ['hello', 'world'],
  ['goodbye', 'moon'],
  ['hello', 'sun']
]

const allWords = flat(words)
// ['hello', 'world', 'goodbye', 'moon', 'hello', 'sun']

Handling Number Arrays

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]

Handling Null Values

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]

Notes

  1. Depth Parameter: If depth is not specified, defaults to 1
  2. Performance: Time complexity depends on the nesting depth of the array
  3. Null Values: Preserves null and undefined values
  4. Non-array Elements: Non-array elements are preserved

Differences from Other Functions

  • flat: Flatten nested arrays
  • flatten: Similar functionality, but may have different implementations
  • flattenDeep: Complete flattening

Performance

  • Time Complexity: O(n × d), where n is the total number of elements, d is the depth
  • Space Complexity: O(n)
  • Use Cases: Data processing and array operations

Released under the MIT License.