Before taking the dive into the concept of array flattening let's understand what are nested arrays.
Nested arrays are nothing just an array inside another array. Nested arrays are used to handle complex data in organise way that cannot be represented by a linear array.
Code Example :
const numbers = [1, 2, [3, 4], 5];
console.log(numbers[2]); // [3, 4]
console.log(numbers[2][0]); // 3
console.log(numbers[2][1]); // 4
how above code work
index 2 gives -> [ 3 , 4 ]
[2][0] gives -> 3
So , now we understand nested arrays but what is array flattening ?
Array flattening is a process to combine multi-dimensional (nested) arrays by extracting all sub-arrays into a singe main array.
what is the use case of array flattening ?
Api response : when real world data arrive from sever it may be a nested array. So we combine multiple array into one single array to simplify the response.
const users = [
{ name: "Abhi", skills: ["HTML", "CSS"] },
{ name: "Rahul", skills: ["JS", "React"] }
];
const allSkills = users.map(user => user.skills).flat();
console.log(allSkills);
// ["HTML", "CSS", "JS", "React"]
It makes search and filter easy.
Form Data Processing :
const formSections = [
["name", "email"],
["password", "confirmPassword"]
];
const allFields = formSections.flat();
console.log(allFields);
// ["name", "email", "password", "confirmPassword"]
Now we can perform data validation easily .
Matrix / Grid Problems : It simply calculations and makes searching and filtering easy.
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
const flatMatrix = matrix.flat();
console.log(flatMatrix);
// [1, 2, 3, 4, 5, 6]
Now you get the idea how you can use the concept of array flattening.
There are different approaches to flatten array Let's see the one by one.
Different approaches to flatten array :
Build in methods : JavaScript provides built-in methods to flatten arrays that are optimized and easy to use.
flat() Method:
.flat() is a built-in method that combines elements of all sub-arrays into a single array.
It performs single-level flattening by default.
.flat(2) → Performs flattening up to depth level 2
.flat(Infinity) → Flattens all sub-arrays into a single array
flatMap() Method:
flatMap() is a combination of map() and flat().
It removes the extra array layer from the return value of map().
It is slightly more optimized than using map() and flat() separately.
Code Example :
without flatMap()
const arr = [1, 2, 3];
const result = arr.map(num => [num * 2]);
console.log(result);
// [[2], [4], [6]] nested array
const final = result.flat();
console.log(final);
// [2, 4, 6]
with flatMap()
const arr = [1, 2, 3];
const result = arr.flatMap(num => [num * 2]);
console.log(result);
// [2, 4, 6]
Using foreach() loop :
Loop through array
Check: element is array or not
If array → add all elements
If not → push directly
const arr = [1, [2, 3], [4, 5]];
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
item.forEach(val => result.push(val));
} else {
result.push(item);
}
});
console.log(result);
Common Interview Scenarios :
Flatten Infinite Nested Array :
//input : [1, [2, [3, [4]]]]
//expected output : [1, 2, 3, 4]
1 → not array → push
[2, [3, [4]]] → array → call again
function flatten(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flatten(item)); // recursion
} else {
result.push(item);
}
}
return result;
}
Stack Approach (Iterative) :
Put all elements into a stack
Process one by one
If array → break it and push back
If value → add to result
function flatten(arr) {
let stack = [...arr];
let result = [];
while (stack.length) {
let item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse();
}
Why interviewer ask this ? :
Recursion understanding : can you solve a problem that repeat itself .
Problem Breakdown : Can you handle unknown depth?
Edge Cases : Empty arrays and mixed datatypes .
Conclusion :
In this blog, we learned what nested arrays are and how to convert them into a single array.
We also explored the use cases and interview perspectives of array flattening with practical code examples.
Top comments (0)