# Array Flatten in JavaScript

## What Exactly Are Nested Arrays?

A nested array (or a multi-dimensional array) is simply an array that contains other arrays as its elements.

Think of a standard array as a single-story egg carton. A nested array is more like a shipping crate filled with smaller boxes, some of which might contain even smaller boxes.

**Example:** `const nested = [1, [2, 3], [[4, 5], 6]];`

In the example above, `1` is at the top level, but `4` and `5` are buried three levels deep.

## Why Bother Flattening?

Flattening is the process of reducing the dimensionality of an array. We do this because:

*   **Easier Iteration:** It’s much simpler to run a single `.map()` or `.forEach()` on a flat list than to write recursive loops for every level.
    
*   **Data Consistency:** Many UI components (like dropdowns or tables) expect a simple, linear array of items.
    
*   **Searchability:** Finding a specific value is faster when you don't have to check every "sub-box."
    

## Transformation

When we "flatten," we are essentially taking every element from the inner arrays and pushing them into a new, single-level array while maintaining their original order.

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2f971932-454f-4e49-aa7e-3032577f7046.png align="center")

### How to Flatten Arrays:

## `flat()`

Introduced in ES2019, the `.flat()` method is the gold standard. By default, it flattens one level deep, but you can pass a depth or use `Infinity` to go all the way.

```javascript
const multidimensional = [1, [2, [3, [4]]]];

console.log(multidimensional.flat()); // [1, 2, [3, [4]]]

console.log(multidimensional.flat(Infinity)); // [1, 2, 3, 4]
```

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ddb27ef8-5524-4391-afc6-c440c69a4b8d.png align="center")

## `reduce()` and `concat()`

Before `.flat()` existed, this was the go-to manual method. It helps you understand the **logic** of the transformation: "Take the accumulator, and merge it with the current item."

```javascript
const nested = [1, [2, 3], [4]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
```

## `toString()` and `split()`

If your array only contains numbers or strings, you can convert the whole thing to a string (which removes brackets) and then split it back.

Note: Use this with caution, as it turns everything into strings!

When you see a nested structure, just ask yourself about the **depth**.

*   Is it always one level deep? Use `[].concat(...arr)`.
    
*   Is the depth unknown? Use `.flat(Infinity)`.
    
*   Are you on an older environment (like legacy IE)? You'll need a recursive polyfill.
    

Flattening isn't just about making arrays shorter; it’s about making your data **usable**.
