← Back to libraryQuestion 159 of 468
🧩JavaScript CodingIntermediate

Flatten a Nested Array

📌 Definition:

Turn an arbitrarily nested array like [1, [2, [3, [4]]]] into a flat [1, 2, 3, 4].

📖 Detailed Explanation:

Modern JS has Array.prototype.flat(depth). For arbitrary depth use flat(Infinity). To implement it yourself, use recursion or a stack; reduce with concat is the classic recursive one-liner.

💻 Solutions:
const flatten = (arr) => arr.flat(Infinity);

// Manual recursive implementation:
function flattenDeep(arr) {
  return arr.reduce(
    (acc, x) => acc.concat(Array.isArray(x) ? flattenDeep(x) : x),
    []
  );
}
🔑 Key Points:
  • arr.flat(Infinity) flattens any depth
  • Manual version: reduce + concat + recursion
  • Array.isArray(x) decides recurse vs push
  • Iterative stack version avoids deep recursion limits
🌍 Real-World Example:

Flattening is common when normalizing nested API responses (e.g. categories with sub-categories) into a single list for a test assertion.

🎯 Scenario-Based Interview Question:

flattenDeep crashes with 'Maximum call stack size exceeded' on a 100,000-deep nested array. How do you fix it?