---
title: "flatten"
description: "Flatten a nested array to a given depth, returning a new flattened array while leaving the original nested structure untouched."
canonical_url: "https://core.mhaibaraai.cn/en/docs/utilities/array/flatten"
---
# 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.

```ts
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

See commit history for [src/utilities/array/flatten.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/utilities/array/flatten.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/utilities/array/flatten.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
