flatten

Flatten a nested array to a given depth, returning a new flattened array while leaving the original nested structure untouched.

Usage

flatten flattens a nested array to the specified depth.

import { flatten } from '@movk/core'

const nested = [1, [2, 3], [4, [5, 6]]]
const flat1 = flatten(nested)
console.log(flat1) // [1, 2, 3, 4, [5, 6]]

const flat2 = flatten(nested, 2)
console.log(flat2) // [1, 2, 3, 4, 5, 6]

API

flatten<T>(arr, depth?)

Flatten a nested array to the specified depth.

Parameters

arr
T[] required
The nested array to flatten.
depth
number
The depth to flatten to. Defaults to 1.

Returns

returns
any[]
The flattened array.

Changelog

No recent changes
Copyright © 2024 - 2026 YiXuan - MIT License