Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
6 min read
Array Flatten in JavaScript

Arrays are one of the most fundamental data structures in JavaScript. But what happens when arrays contain other arrays?

This is where nested arrays come into play. In this blog, we’ll explore what nested arrays are, why flattening them is useful, and the different ways to achieve it—from beginner-friendly methods to advanced techniques.


What Are Nested Arrays?

A nested array is simply an array that contains one or more arrays as its elements.

Example

const nestedArray = [1, 2, [3, 4], [5, 6]];

Here, [3, 4] and [5, 6] are arrays inside the main array.

Visual Representation

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

Index:  0   1    2       3
                 |       |
               [3,4]   [5,6]

Nested arrays can go even deeper:

const deeplyNested = [1, [2, [3, [4, 5]]]];
[1
 └── [2
      └── [3
           └── [4, 5]
           ]
      ]
]

Why Is Flattening Arrays Useful?

Flattening converts a nested array into a single-level array. This is particularly helpful in:

  • Data Processing – APIs often return nested data structures.

  • Searching & Filtering – Easier operations on a single-level array.

  • Mathematical Operations – Simplifies calculations like sum or average.

  • UI Rendering – Useful when displaying hierarchical data.

  • Technical Interviews – A commonly asked problem to test recursion and array manipulation.


Example

const nestedArray = [1, 2, [3, 4], [5, 6]];
// Flattened version
[1, 2, 3, 4, 5, 6]

Concept of Flattening Arrays

Flattening involves traversing each element of the array:

  1. If the element is not an array, add it directly to the result.

  2. If the element is an array, recursively extract its elements.

  3. Continue until all nested levels are processed.

Step-by-Step Example

const arr = [1, [2, [3, 4]], 5];
Step Current Element Result
1 1 [1]
2 [2, [3, 4]] Explore inside
3 2 [1, 2]
4 [3, 4] Explore inside
5 3, 4 [1, 2, 3, 4]
6 5 [1, 2, 3, 4, 5]

Different Approaches to Flatten Arrays

1. Using Array.prototype.flat()

The flat() method is the simplest way to flatten arrays.

const arr = [1, [2, [3, 4]], 5];

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

Pros

  • Easy to use

  • Built-in and readable

Cons

  • Not supported in very old browsers

2. Using Recursion

Recursion is a popular approach that demonstrates problem-solving skills.

function flattenArray(arr) {
  let result = [];

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

  return result;
}

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArray(arr)); // [1, 2, 3, 4, 5]

Why It’s Important

  • Shows understanding of recursion

  • Frequently asked in coding interviews


3. Using reduce()

const flattenArray = (arr) => {
  return arr.reduce((acc, element) => {
    return acc.concat(
      Array.isArray(element) ? flattenArray(element) : element
    );
  }, []);
};

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArray(arr));

Pros

  • Elegant and concise

  • Demonstrates knowledge of functional programming


4. Using an Iterative Approach with a Stack (Advanced)

This approach avoids recursion and is efficient for deeply nested arrays.

function flattenArrayIterative(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();
}

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArrayIterative(arr));

Pros

  • Prevents call stack overflow

  • Suitable for very deep nesting


5. Flattening to a Specific Depth

function flattenToDepth(arr, depth = 1) {
  if (depth === 0) return arr;

  return arr.reduce((acc, element) => {
    if (Array.isArray(element)) {
      return acc.concat(flattenToDepth(element, depth - 1));
    }
    return acc.concat(element);
  }, []);
}

console.log(flattenToDepth([1, [2, [3, [4]]]], 2));
// Output: [1, 2, 3, [4]]

Common Interview Scenarios

1. Fully Flatten an Array

flatten([1, [2, [3, 4]], 5]);
// Expected Output: [1, 2, 3, 4, 5]

2. Flatten to a Specific Depth

flatten([1, [2, [3, 4]]], 1);
// Output: [1, 2, [3, 4]]

3. Flatten and Remove Duplicates

const uniqueFlatten = (arr) =>
  [...new Set(arr.flat(Infinity))];

console.log(uniqueFlatten([1, [2, 2, [3, 4, 4]]]));
// Output: [1, 2, 3, 4]

4. Flatten and Sum Values

const sum = (arr) =>
  arr.flat(Infinity).reduce((a, b) => a + b, 0);

console.log(sum([1, [2, [3, 4]], 5])); // 15

Problem-Solving Thinking

When approaching a flattening problem, ask yourself:

  1. What is the depth of nesting?

  2. Should the flattening be partial or complete?

  3. Is recursion safe, or should an iterative approach be used?

  4. Are there additional constraints like uniqueness or ordering?


Comparison of Approaches

Approach Readability Performance Interview Value Best Use Case
flat() ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐ Everyday use
Recursion ⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ Interviews
reduce() ⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐ Functional style
Iterative Stack ⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ Deep nesting

Conclusion

Nested arrays are common in real-world applications, and understanding how to flatten them is an essential JavaScript skill. Whether you use the built-in flat() method for simplicity or implement recursive and iterative solutions for interviews, mastering these techniques will strengthen your problem-solving abilities.

If you found this article helpful, feel free to share it with others and leave your thoughts/feedback in the comments. Happy coding!