Array Flatten in JavaScript
What nested arrays are :-
Simply we Can say that Nested array means array inside another array . As a element of that array . And we can also access the inside array element by it's indexes .
const nestedarr=[1,2,3,4,[5,6,7],8,9];
Above is the example of nested array . As we can see that at index 4 another array as a element in nestedarr.
What Array flatten is :-
Converting nested array into single dimensional array is called array flatten Where all element should brought to same level .
Why flattening arrays is useful:-
Simplifies data processing .
Making easier to filter, search, sort and render array.
UI Rendering.
API Normalization.
Different approaches to flatten arrays
Their are many approaches for the array flatten in JavaScript . As according to the our use case we use them .
Let's discuss them
1 :- Native approach (array.prototype.flat())
This is the most common or build in approach used in JavaScript for array flattening . where flat(number) takes number as a argument which tells about the nesting level of the array to be flatten So it takes 1 level as a default.
const shalowFlat = deeplyNested.flat() // 1 level flat
console.log(shalowFlat) // output: [1,2,[3,4],5,6]
const deepFlat = deeplyNested.flat(Infinity) // completely flat
console.log(deepFlat) // output: [1,2,3,4,5,6]
2:-Iterative Approach :-
Using while loop and stack Data Structure to approach array flatten.
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next); // Push elements back onto the stack
} else {
result.unshift(next); // Add to the front to maintain order
}
}
return result;
}
3:-Recursive Approach:-
This approach is commonly used in the interviews . In this we approach using traversing each element found to be array recursion takes place and the push each element into the array.
function flattenDeep(arr) {
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flattenDeep(item));
} else {
result.push(item);
}
}
return result;
}



