# Array Flatten in JavaScript

Hi everyone , in this article we are going to explore the flat method of the `Array` instance, the nested arrays , how flatterning the array is useful and lot more.

### What are the nested arrays

Nested arrays are simply **arrays inside other arrays**.

Example :

```javascript
let numbers = [[1, 2], [3, 4], [5, 6]];
```

> Here in this example, there are three arrays inside the one main array.
> 
> The outer array :
> 
> ```javascript
> [[1, 2], [3, 4], [5, 6]]
> ```
> 
> The inner arrays :
> 
> ```javascript
> [1, 2]
> [3, 4]
> [5, 6]
> ```

### Why flattening arrays is useful

Flattening arrays means converting a **nested array (arrays inside arrays)** into a **simple flat structure array.** It sounds simple, but it solves a lot of practical problems.

> Most array methods in JavaScript (`map`, `filter`, `reduce`) expect a **flat structure**.

Example :

```javascript
let users = [
  { name: "A", posts: ["p1", "p2"] },
  { name: "B", posts: ["p3"] }
];

// In javascript we have flat function to flattern the array.
let allPosts = users.map(u => u.posts).flat();
// ["p1", "p2", "p3"]
```

### Different approaches to flatten arrays

### 1\. `Array.prototype.flat()`

The `flat()` method of `Array` instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Example :

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

console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, [2, [3, [4, 5]]]];

console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]

console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]

console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]

```

### 2\. Using Recursion

Recursion involves a function calling itself to break down nested arrays until only primitive values remain. This method is readable but can cause **stack overflow errors** for extremely deep arrays.

```javascript
function flattenRecursive(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenRecursive(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}   
```

> In this example, we are runningthe loop over the outer most array till its length. Inside that we are handling the array seperately. If on any index the strucutre is of type array again return the same function with the new nested array.

### 3.**Iterative Approach (Stack)**

An iterative approach uses a **stack** (last-in, first-out) to handle nesting without recursion, avoiding stack overflow issues. It processes elements by popping from the stack and pushing non-array items to the result.

```javascript
function flattenIterative(arr) {
  const stack = [...arr];
  const result = [];
  while (stack.length > 0) {
    const item = stack.pop();
    if (Array.isArray(item)) {
      stack.push(...item); // Unwrap and push back
    } else {
      result.push(item);
    }
  }
  return result.reverse(); // Reverse to maintain original order
}   
```
