Array Flattening
Frequently, we are thrown with a question where the interviewer expects us to make a nested array to a single array (in other terms, flatten an array). Although we have an existing Array method to flatten the array but sometimes they expects us to write our own implementation. Today I will discuss about the question and the approaches to solve them.
Question : Given a nested array on any depth and we need to make it a single array.Eg. :- Array = [1,2,[3,4,[5,6],7],8] || [1,2,[3,4],5] || [1,2,[3,[4,[5]]]]Output :- [1,2,3,4,5,6,7,8] | [1,2,3,4,5] || [1,2,3,4,5] || [1,2,3,4,5]
respectively for every input array
First Approach :- Using inbuilt Array method
Array.prototype.flat() :-
The flat() method creates a new array with all sub array elements concatenated into it recursively up to the specified the depth of the array, where depth specifies how deep a nested array structure should be flattened. By default it’s value is 1.
Syntax :- flat(depth) where the depth specifies the level of nesting.
Flatten 1 level deep
const arr1 = [1, 2, [3, 4]]arr1.flat();
ouptut - [1, 2, 3, 4]const arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat();output - [1, 2, 3, 4, [5, 6]]// Flatten 2 levels deepconst arr3 = [2, 2, 5, [5, [5, [6]], 7]];arr3.flat(2);output - [2, 2, 5, 5, 5, [6], 7];** For flattening every level depth we need to pass 'Inifinity' as aurguments to the flat() method **// Flatten all levelsconst arr4 = [2, 2, 5, [5, [5, [6]], 7]];arr4.flat(Infinity);output - [2, 2, 5, 5, 5, 6, 7]; For reference please click here
Second Approach:- Writing our own implementation for the flattening
There are different approaches to write the flat() method, few are below.
Here is the fastest solution, which works also on arrays with multiple levels of nesting:
const flatten = function(arr, result = []) { for (let i = 0, length = arr.length; i < length; i++) { const value = arr[i];
if(Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
} return result;}Reference taken from here
The above method may not work for huge arrays, so below is another implementation for the same . You can also try this for deep flattening:
function deepFlatten(arr) {
return flatten( // return shalowly flattened array
arr.map(x=> // with each x in array
Array.isArray(x) // is x an array?
? deepFlatten(x) // if yes, return deeply flattened x
: x // if no, return just x
)
)
}Reference taken from here
Hope this article will be of some help. All the best !!