Array Flatten in JavaScript

What are Nested Arrays?
A nested array is simply an array inside another array.
Nested arrays are arrays that contain other arrays as their elements, forming a "set within a set" structure, commonly referred to as arrays of arrays. They are used to represent complex, multi-dimensional data like matrices, grids, or hierarchical data structures, where elements are accessed using multiple indexes.
Example:
[1, 2, [3, 4], 5]
Think of it like a box inside a box :
Main Box
├── 1
├── 2
├── [3, 4] <- inner box
└── 5
Why Flattening Arrays is Useful?
Flattening = converting nested structure into a single-level array
Before:
[1, [2, 3], [4, [5, 6]]]
After:
[1, 2, 3, 4, 5, 6] // this is the sorted array
Real Use Cases:
API responses (nested JSON)
UI rendering (lists inside lists)
Data processing (analytics, filters)
Removing complexity for algorithms
In short: Machines love flat data
Concept of flattening arrays
Flattening an array is the process of converting a nested, multi-dimensional array (e.g., [[1, 2], [3, 4]]) into a single-dimensional, flat array ([1, 2, 3, 4]). It simplifies complex data structures, making them easier to process, iterate over, or display by removing layers of nesting, often using methods like JavaScript's flat().
Key Concepts of Array Flattening:
Depth Control: Flattening can be shallow (first level only) or deep (removing all nesting). In JavaScript, array.flat(depth) accepts an optional depth parameter to determine how many levels to flatten.
Infinite Depth: By using Infinity (e.g., array.flat(Infinity)), you can recursively flatten an array of unknown or multiple nested levels into a 1D array.
Use Cases: Essential for simplifying data from API responses, processing nested JSON, or flattening arrays of tagged items.
Built-in Functions: JavaScript
flat()(ES2019) ornumpy.flatten()in Python.flatMap(): Combines mapping and flattening into one efficient step, mapping each element and then flattening it by one level.Recursion: Used to flatten deeply nested structures when
flat()isn't available or specialized control is needed.
Example:
const nestedArray = [1, [2, [3, [4]]]];
const flattened = nestedArray.flat(Infinity);
// Output: [1, 2, 3, 4]
Common Approaches (JavaScript):
array.flat(depth): The easiest method for reducing nesting.reduce()andconcat(): An older, effective method to flatten arrays.Spread Operator (
...): Good for shallow flattening.
Flattening Arrays in JavaScript
1. flat() - simplest
const arr = [1, [2, [3, [4]]]];
arr.flat(); // [1, 2, [3, [4]]] — 1 level (default)
arr.flat(2); // [1, 2, 3, [4]] — 2 levels
arr.flat(Infinity); // [1, 2, 3, 4] — all levels
2. flatMap() - map + flatten together
// Only flattens 1 level, but great for transformations
[1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
// Useful for filtering + flattening
[1, 2, 3].flatMap(x => x > 1 ? [x] : []); // [2, 3]
3. reduce + concat -- manual control
// One level
arr.reduce((acc, val) => acc.concat(val), []);
// Deep (recursive)
const flatten = arr =>
arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
4. Recursive - readable deep flatten
function flatten(arr) {
return arr.flatMap(item =>
Array.isArray(item) ? flatten(item) : item
);
}
5. Iterative (stack-based) - safest for large/deep arrays
function flatten(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
Array.isArray(item) ? stack.push(...item) : result.unshift(item);
}
return result;
}
6. Generator - lazy, memory-efficient
function* flatten(arr) {
for (const item of arr) {
Array.isArray(item) ? yield* flatten(item) : yield item;
}
}
[...flatten([1, [2, [3]]])] // [1, 2, 3]
When to use what
| Method | Best for |
|---|---|
flat(Infinity) |
Quick, simple, modern codebase |
flatMap() |
Mapping and flattening in one step |
reduce |
Custom logic during flattening |
| Recursive | Readable deep flattening |
| Stack-based | Very large or deeply nested arrays |
| Generator | Lazy evaluation, streaming large data |
Common Array Flattening Interview Scenarios:
1. "Flatten one level deep"
// Simplest case — interviewers test if you know flat()
const arr = [1, [2, 3], [4, 5]];
arr.flat(); // [1, 2, 3, 4, 5]
// Or manually:
arr.reduce((acc, val) => acc.concat(val), []);
[].concat(...arr);
2. "Flatten to arbitrary depth" (most common)
// Recursive — what most interviewers want to see you write
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
3. "Flatten without recursion" (follow-up challenge)
// Stack-based — shows you can avoid stack overflow on deep arrays
function flatten(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
Array.isArray(item) ? stack.push(...item) : result.unshift(item);
}
return result;
}
4. "Flatten to a specific depth" (depth-aware)
function flatten(arr, depth = 1) {
return arr.reduce((acc, val) =>
Array.isArray(val) && depth > 0
? acc.concat(flatten(val, depth - 1))
: acc.concat(val),
[]);
}
flatten([1, [2, [3, [4]]]], 2); // [1, 2, 3, [4]]
5. "Flatten an object/nested keys" (tricky variant)
function flattenObj(obj, prefix = '') {
return Object.entries(obj).reduce((acc, [key, val]) => {
const newKey = prefix ? `\({prefix}.\){key}` : key;
return typeof val === 'object' && val !== null && !Array.isArray(val)
? { ...acc, ...flattenObj(val, newKey) }
: { ...acc, [newKey]: val };
}, {});
}
flattenObj({ a: { b: { c: 1 } }, d: 2 });
// { 'a.b.c': 1, d: 2 }
6. "Remove duplicates after flattening" (chained logic)
const arr = [1, [2, 2], [3, [3, 4]]];
const result = [...new Set(arr.flat(Infinity))];
// [1, 2, 3, 4]
What interviewers are really testing
| Scenario | They're checking |
|---|---|
| Basic flatten | Do you know built-ins? |
| Recursive flatten | Can you think recursively? |
| No-recursion flatten | Do you know stack overflow risks? |
| Depth-controlled | Can you generalize a solution? |
| Object flatten | Can you adapt the pattern to new structures? |
| Dedup after flatten | Can you chain transformations cleanly? |
Conclusion:
Array flattening is the process of transforming a nested array structure into a single-level array, making data easier to process, manipulate, and use in real-world applications like APIs, UI rendering, and data transformation.
JavaScript provides multiple ways to achieve this:
Built-in methods like
.flat()for quick and simple solutionsRecursive approaches for handling deeply nested structures (most important for interviews)
Iterative techniques using stacks for optimized control and avoiding recursion limits
The key to mastering array flattening lies in understanding the core idea:
Identify whether an element is an array, and if so, break it down until all values are extracted.
From a problem-solving perspective, it teaches:
Recursion and divide-and-conquer thinking
Handling tree-like data structures
Writing clean and scalable logic
In short, array flattening is not just about arrays it's a foundational concept that strengthens your ability to solve complex nested data problems efficiently.




