DEV Community

Bhupesh Chandra Joshi
Bhupesh Chandra Joshi

Posted on

Flattening Nested Arrays in JavaScript: A Complete Guide for Developers & Interview Success

Visual 1: Nested Array Structure

const nested = [1, [2, 3], [4, [5, [6, 7]]]];
Enter fullscreen mode Exit fullscreen mode

*By Bhupesh – JavaScript Developer *

Published on Dev.to – April 2026

Hey there! If you’ve ever stared at deeply nested data from an API and wondered how to turn it into something usable, you’re not alone. As a JavaScript developer who’s shipped production apps at scale, I’ve seen flattening nested arrays come up in real projects and technical interviews more times than I can count.

In this post, we’ll go from the fundamentals to advanced problem-solving techniques — exactly the kind of deep-dive content you’d find in top-tier books like Eloquent JavaScript (Marijn Haverbeke) and Introduction to Algorithms (Cormen et al.). By the end, you’ll not only understand how to flatten arrays but why the different approaches matter.

Let’s flatten some arrays! 🚀

1. What Are Nested Arrays?

A nested array (also called a multi-dimensional array) is simply an array that contains other arrays as elements. These can be one level deep or many levels deep.

// Example of a 3-level nested array
const data = [
  10,
  [20, 30],
  [40, [50, 60, [70, 80]]]
];
Enter fullscreen mode Exit fullscreen mode

Think of it like a tree:

  • The root is your main array.
  • Each branch is a sub-array.
  • Leaves are the primitive values (numbers, strings, etc.).

This structure appears everywhere: API responses with categories and sub-categories, file system trees, comment threads, or even game level data.

Visual 2: Flatten Transformation (Before → After)

2. Why Flattening Arrays Is Actually Useful

Flattening isn’t just a neat trick — it solves real problems:

  • Data normalization: Many libraries (charts, tables, search indexes) expect flat data.
  • API responses: JSON often arrives deeply nested for a reason (hierarchy), but your UI or business logic needs it flat.
  • Performance & readability: Looping, filtering, mapping, or reducing becomes trivial on a 1D array.
  • Algorithms: Searching, sorting, or deduplication is faster and simpler.
  • Real-world examples:
    • E-commerce: Flatten product categories + sub-categories into tags.
    • Analytics: Flatten event logs with nested user journeys.
    • Forms: Flatten validation error objects.

Mastering this shows you can think about data shape — a skill that separates junior from senior developers.

3. The Core Concept of Flattening

Flattening = converting a multi-dimensional array into a single-dimensional array.

There are two important variations:

  • Shallow flatten (1 level only)
  • Deep flatten (all levels, any depth)

The recursive idea is beautifully simple (straight from classic algorithm books):

For each element in the array:

• If it is not an array → just add it to the result.

• If it is an array → flatten it first, then add its contents.

This is exactly how tree traversal works — and arrays are just trees with a linear interface.

4. Different Approaches to Flatten Arrays (With Step-by-Step Thinking)

Approach 1: Modern Built-in — Array.prototype.flat() (Recommended for production)

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

const flattened = nested.flat(Infinity); // Deep flatten
console.log(flattened); // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Why it’s great:

  • One line.
  • Accepts a depth parameter (default = 1).
  • Highly optimized by the JS engine.

When to use: Everyday code (ES2019+).

Approach 2: Recursive Solution (Interview Favorite)

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

  for (let item of arr) {
    if (Array.isArray(item)) {
      // Recursive call — this is the "magic"
      result = result.concat(flattenRecursive(item));
    } else {
      result.push(item);
    }
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Step-by-step problem-solving thinking:

  1. Start with an empty result array.
  2. Loop through every element.
  3. Decision point: Is it an array? → Recurse and concat. Else → push.
  4. Return the accumulated result.

This mirrors exactly how you’d traverse a tree. Time complexity: O(n) where n is the total number of elements.

Approach 3: Functional Style with reduce() (Elegant & Declarative)

const flattenReduce = (arr) =>
  arr.reduce((acc, item) =>
    acc.concat(Array.isArray(item) ? flattenReduce(item) : item), []
  );
Enter fullscreen mode Exit fullscreen mode

Beautiful, but still recursive under the hood. Great for showing functional programming skills.

Approach 4: Iterative with Stack (Best for very deep nesting)

Recursion can hit stack limits on extremely deep arrays. Here’s the iterative version:

function flattenIterative(arr) {
  const result = [];
  const stack = [...arr]; // Copy input

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

    if (Array.isArray(current)) {
      stack.push(...current); // Push children onto stack
    } else {
      result.unshift(current); // Add to front (or use reverse at end)
    }
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Why this shows senior thinking: You understand recursion depth limits and can provide a non-recursive alternative.

Approach 5: flatMap() for specific cases

Useful when you want to transform and flatten in one go (e.g., doubling values while flattening).

5. Common Interview Scenarios & How to Nail Them

Interviewers love this question because it tests recursion, data structures, edge cases, and communication.

Typical question:

“Write a function flattenArray that takes a nested array and returns a flat array. Do not use Array.flat().”

Follow-up questions they will ask:

  • What if the array contains non-primitive values (objects, null, strings)?
  • Handle limited depth only?
  • Time and space complexity?
  • Can you do it iteratively?
  • What about [[[1]]] or [] or [1, 2, 3] (already flat)?

Pro tip for interviews:

  1. Clarify requirements first (“Deep or shallow? Handle non-arrays?”).
  2. Start with the recursive solution (easiest to explain).
  3. Then offer the iterative version to show depth.
  4. Analyze complexity out loud: “O(n) time, O(n) space in worst case due to recursion stack.”

LeetCode-style variant: 341. Flatten Nested List Iterator (requires iterator pattern — even more advanced).

Final Thoughts: Level Up Your JavaScript Thinking

Flattening nested arrays is more than a coding trick — it trains you to think about data transformation, recursion vs iteration, and trade-offs. These are the exact skills that separate developers who “make it work” from those who design elegant, maintainable solutions.

Whether you’re preparing for your next big interview or refactoring production code, mastering this pattern will make you faster and more confident.

Want to go deeper?

I regularly mentor developers on advanced JavaScript, system design, and interview preparation. If you’re looking to level up your skills or need help with a specific project, feel free to reach out — I’d love to help you grow.

Happy coding! 💻


Did this article help you? Drop a comment below with your favorite flattening method or a tricky nested array you’ve encountered in the wild. I read every single one!

Follow me for more practical, interview-focused JavaScript deep dives.

Top comments (0)