close

DEV Community

Souvik Guha Roy
Souvik Guha Roy

Posted on

Array Flatten in JavaScript

Working with arrays is common in JavaScriptโ€”but sometimes arrays can get nested, making them harder to use. Thatโ€™s where array flattening comes in.

In this blog, weโ€™ll break down what nested arrays are, why flattening is useful, and explore different ways to flatten arrays step by step.


๐Ÿ“ฆ What Are Nested Arrays?

A nested array is simply an array inside another array.

Example:

```js id="ex1"
const arr = [1, 2, [3, 4], [5, [6, 7]]];




Here:

* `[3, 4]` is a nested array
* `[5, [6, 7]]` is **deeply nested**

---

## ๐Ÿง  Visual Representation

### Nested Structure:



```id="viz1"
[ 
  1,
  2,
  [3, 4],
  [5, [6, 7]]
]
Enter fullscreen mode Exit fullscreen mode

Think of it like layers:

Level 1 โ†’ 1, 2
Level 2 โ†’ 3, 4, 5
Level 3 โ†’ 6, 7
Enter fullscreen mode Exit fullscreen mode

โ“ Why Flattening Arrays Is Useful

Flattening converts a nested array into a single-level array.

Example:

```js id="ex2"
Input: [1, 2, [3, 4], [5, [6, 7]]]
Output: [1, 2, 3, 4, 5, 6, 7]




### ๐Ÿ’ก Use Cases:

* API responses with nested data
* Data processing & transformation
* Simplifying loops and operations
* Preparing data for UI rendering

---

## ๐Ÿ”„ Concept of Flattening Arrays

Flattening means:

> โ€œTake elements from all nested levels and bring them into one level.โ€

---

## ๐Ÿ› ๏ธ Different Approaches to Flatten Arrays

---

### 1. Using `flat()` (Built-in Method)

The easiest way in modern JavaScript.



```js id="code1"
const arr = [1, 2, [3, 4], [5, [6, 7]]];

const flatArr = arr.flat(2);

console.log(flatArr);
// [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Notes:

  • flat(depth) defines how deep to flatten
  • Use Infinity for full flattening

```js id="code2"
arr.flat(Infinity);




---

### 2. Using Recursion (Most Important for Interviews)

This is the **classic interview approach**.



```js id="code3"
function flattenArray(arr) {
  let result = [];

  for (let item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flattenArray([1, [2, [3, 4]], 5]));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Step-by-Step Thinking

  1. Loop through array
  2. Check:
  • If element is array โ†’ flatten again
  • Else โ†’ push to result
    1. Combine results

3. Using reduce()

A functional approach:

```js id="code4"
const flattenArray = (arr) =>
arr.reduce((acc, curr) => {
return acc.concat(
Array.isArray(curr) ? flattenArray(curr) : curr
);
}, []);

console.log(flattenArray([1, [2, [3]], 4]));




---

### 4. Using Stack (Iterative Approach)

Avoids recursion:



```js id="code5"
function flattenArray(arr) {
  const stack = [...arr];
  const result = [];

  while (stack.length) {
    const next = stack.pop();

    if (Array.isArray(next)) {
      stack.push(...next);
    } else {
      result.push(next);
    }
  }

  return result.reverse();
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Š Flatten Transformation Visual

[1, [2, [3, 4]], 5]

Step 1 โ†’ [1, 2, [3, 4], 5]
Step 2 โ†’ [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Common Interview Scenarios

1. Flatten to Specific Depth

```js id="code6"
function flattenDepth(arr, depth) {
if (depth === 0) return arr;

return arr.reduce((acc, curr) => {
if (Array.isArray(curr)) {
acc.push(...flattenDepth(curr, depth - 1));
} else {
acc.push(curr);
}
return acc;
}, []);
}




---

### 2. Infinite Flatten



```js id="code7"
flattenArray(arr); // recursive solution
Enter fullscreen mode Exit fullscreen mode

3. Edge Cases Interviewers Test

  • Empty array โ†’ []
  • No nesting โ†’ same array
  • Deep nesting โ†’ performance check

๐Ÿงฉ Problem-Solving Mindset

When solving flatten problems, think:

  • โœ” Is recursion needed?
  • โœ” Can I reduce complexity?
  • โœ” What is the depth?
  • โœ” Should I preserve order?

๐Ÿš€ Final Thoughts

Array flattening is a must-know concept in JavaScript because it:

  • Strengthens recursion skills
  • Improves problem-solving ability
  • Appears frequently in interviews

Start with flat() for real projects, but master recursion for interviews.


Top comments (0)