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 different approaches to solve them.
Question: Given a nested array of any depth & 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] 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 arr = [1, 2, [3, 4]]
arr.flat();
// output - [1, 2, 3, 4]
const arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
// output - [1, 2, 3, 4, [5, 6]]
// Flatten 2 levels deep
const arr = [2, 2, 5, [5, [5, [6]], 7]];
arr.flat(2);
// output - [2, 2, 5, 5, 5, [6], 7];
** For flattening every level depth we need to pass **'Inifinity'** as **arguments** to the flat() method**
// Flatten all levels
const arr = [2, 2, 5, [5, [5, [6]], 7]];
arr.flat(Infinity);
// output - [2, 2, 5, 5, 5, 6, 7];
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;
}
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
)
)
}
Hope this article will be of some help. All the best !!