Array Flatten in JavaScript

1) What Nested Arrays Are
A nested array is an array that contains one or more arrays inside it. In simple terms, it’s like an array within another array. This allows you to store more complex data structures, such as tables, grids, or grouped data.
Key Points About Nested Arrays :
A nested array is an array inside another array.
Each inner array can have its own values and length.
You can access elements using multiple indices.
Useful for representing matrices, tables, or grouped data.
Example :
numbersis the main (outer) array.It contains smaller (inner) arrays.
To access elements, we use two indices →
[outer][inner].
// Nested array
let numbers = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(numbers); // Before: [[1,2,3],[4,5,6],[7,8,9]]
// Access element 5
let value = numbers[1][1];
console.log(value); // Output: 5
Visual Representation :
numbers = [
[1, 2, 3], // index 0
[4, 5, 6], // index 1
[7, 8, 9] // index 2
]
Accessing:
numbers[1] → [4, 5, 6]
numbers[1][1] → 5
Output :
Before: [[1,2,3],[4,5,6],[7,8,9]]
After accessing numbers[1][1]: 5
2) Why Flattening Arrays is Useful
Flattening an array means converting a nested array (arrays inside arrays) into a single-level array. This makes the data easier to work with, especially when performing operations like looping, searching, or calculations.
Key Points About Flattening Arrays :
It removes nesting and creates a one-dimensional array.
Makes it easier to iterate through all elements.
Simplifies data processing and transformations.
Useful when working with APIs or complex data structures.
Example :
numbersis a nested array.After flattening, all values come into a single array.
// Nested array
let numbers = [1, [2, 3], [4, 5]];
console.log(numbers); // Before: [1, [2, 3], [4, 5]]
// Flatten the array
let flatNumbers = numbers.flat();
console.log(flatNumbers); // Output: [1, 2, 3, 4, 5]
Step-by-Step Idea :
[1, [2, 3], [4, 5]]
↓
Take values out of inner arrays
↓
[1, 2, 3, 4, 5]
Before vs After :
Before: [1, [2, 3], [4, 5]]
After: [1, 2, 3, 4, 5]
3) Concept of Flattening Arrays
Flattening an array means converting a nested (multi-level) array into a single-level array. In other words, it removes all inner arrays and brings every element into one continuous list.
Key Points About Flattening Arrays :
It transforms multi-dimensional arrays into a one-dimensional array.
All elements are moved to the same level.
It helps simplify complex data structures.
Makes operations like looping, searching, and calculations easier.
Example :
datais a nested array with multiple levels.After flattening, all elements come into one array.
// Nested array
let data = [1, [2, [3, 4]], 5];
console.log(data); // Before: [1, [2, [3, 4]], 5]
// Flatten the array completely
let flatData = data.flat(2);
console.log(flatData); // Output: [1, 2, 3, 4, 5]
Step-by-Step Concept :
[1, [2, [3, 4]], 5]
↓
Remove one level
[1, 2, [3, 4], 5]
↓
Remove next level
[1, 2, 3, 4, 5]
Visual Idea :
Levels:
Level 1 → [1, ___ , 5]
Level 2 → [2, ___]
Level 3 → [3, 4]
Flatten → All levels merged → [1, 2, 3, 4, 5]
Before vs After :
Before: [1, [2, [3, 4]], 5]
After: [1, 2, 3, 4, 5]
4 ) Different Approaches to Flatten Arrays
There are multiple ways to flatten arrays in JavaScript. The method you choose depends on how deeply nested your array is and your use case.
Key Points About Flattening Approaches :
Some methods are simple but work only for shallow arrays.
Others handle deeply nested arrays.
Different approaches offer flexibility and control.
1) Using .flat() Method
Easiest and most commonly used
You can control how deep to flatten
let arr = [1, [2, [3, 4]], 5];
let result = arr.flat(2);
console.log(result); // Output: [1, 2, 3, 4, 5]
ii ) Using .flat(Infinity)
- Flattens all levels regardless of depth.
let arr = [1, [2, [3, [4, 5]]]];
let result = arr.flat(Infinity);
console.log(result); // Output: [1, 2, 3, 4, 5]
iii ) Using reduce()
- Useful when you want more control or compatibility.
let arr = [1, [2, 3], [4, 5]];
let result = arr.reduce((acc, val) => acc.concat(val), []);
console.log(result); // Output: [1, 2, 3, 4, 5]
iv ) Using Recursion
- Best for deeply nested arrays when
.flat()is not used.
function flatten(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
}
return result;
}
let arr = [1, [2, [3, 4]], 5];
console.log(flatten(arr)); // Output: [1, 2, 3, 4, 5]
v ) Using toString() (Not Recommended)
Converts array to string and back.
Works only for simple numeric/string arrays.
let arr = [1, [2, 3], [4, 5]];
let result = arr.toString().split(',').map(Number);
console.log(result); // Output: [1, 2, 3, 4, 5]
Visual Comparison :
Nested: [1, [2, [3, 4]], 5]
.flat(): Easy, built-in
reduce(): One level
recursion: Full control (best for interviews)
Result: [1, 2, 3, 4, 5]
5 ) Common Interview Scenarios (Flattening Arrays)
Flattening arrays is a very common topic in coding interviews, especially to test your understanding of recursion, array methods, and problem-solving skills.
Key Points Interviewers Look For :
Understanding of nested structures
Ability to handle unknown depth
Clean and efficient logic
Knowledge of built-in methods vs custom solutions
i ) Flatten a Deeply Nested Array
Most common interview question
Depth is unknown
function flatten(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
}
return result;
}
let arr = [1, [2, [3, [4, 5]]]];
console.log(flatten(arr)); // Output: [1, 2, 3, 4, 5]
ii ) Flatten Array Using .flat()
- Tests knowledge of modern JavaScript
let arr = [1, [2, [3, 4]], 5];
let result = arr.flat(Infinity);
console.log(result); // Output: [1, 2, 3, 4, 5]
iii ) Flatten Only One Level
- Tests understanding of shallow vs deep flattening
let arr = [1, [2, 3], [4, [5]]];
let result = arr.flat(1);
console.log(result); // Output: [1, 2, 3, 4, [5]]
iv ) Flatten Without Using Built-in Methods
- Very important for interviews
function flatten(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
});
return result;
}
v ) Flatten and Remove Duplicates
- Combines multiple concepts
let arr = [1, [2, 3], [2, 4, [1, 5]]];
let result = [...new Set(arr.flat(Infinity))];
console.log(result); // Output: [1, 2, 3, 4, 5]
vi ) Flatten and Sum All Values
- Tests logic + iteration
let arr = [1, [2, [3, 4]], 5];
let sum = arr.flat(Infinity).reduce((acc, val) => acc + val, 0);
console.log(sum); // Output: 15
summary
Flattening arrays is the process of converting a nested array (arrays inside arrays) into a single-level array where all elements are placed in one list. It is useful because it simplifies data, making it easier to loop through, search, and perform operations. The core idea is simple: if an element is an array, open it and extract its values; if it is a normal value, keep it. This process is commonly done using methods like .flat(), reduce(), or recursion, and is an important concept in problem-solving and coding interviews.




