Hello all๐,
In this series we will see a lot of question that are asked in javascript interviews so get ready for it
In this article we will see How to flatten an deeply nested array for example
[1,[2,3,[4,5]]] and convert in into [1,2,3,4,5]
We will learn to flatten an array in 2 ways
Using built in function (
flat()
)Using recursion
1. Using Flat()
method in Javascript
The flat()
method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array, and flats upto the specified depth.
var newArr = arr.flat(depth)
By default, the depth limit is 1. It can be 1 to Infinity
.
const arr = [1,[2,3,[4,5]]];
// Setting the depth value to
// Infinity to deep flatten the array
const flattened = arr.flat(Infinity);
console.log(flattened)
// Output [1,2,3,4,5]
2. Recursively flat an array (Pollyfill)
Now we will see how do it without using any builtin function or basically writing the pollyfill for flat function
//Flatten an array using recursion
const arr = [1,[2,3,[4,5]]]
const flatten = (input)=>{
let result = []
if(!Array.isArray(input)) {
return input;
}
for(let data of input) {
result = result.concat(flatten(data))
}
return result
}
console.log(flatten(arr))
// Output [1,2,3,4,5]
Let me explain the code
- Iterate through each and every value of an array and check whether it is value or an array using
Array.isArray()
method. - If it is a value return it and concat it.
- If it is an array then follow again from step 1.
Using ES6 features (using reduce()
)
function flatten(arr) {
return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
};
const arr = [1,[2,3,[4,5]]];
const flattened = flatten(arr);
console.log(flattened);
// Output [1,2,3,4,5]
For better understanding of the code Please refer to the gif below.
You can also check this Github repo for the code
Voila๐
Let me know your thoughts about it ๐ and if you like it share it with others.
Top comments (8)
Ok, that is cool but what if I have a way more complex structure with objects and nested arrays with objects?
Would it be possible to flatten this into, lets say in somekind of table structure to make searching easier und reverse it after searching?
Thanks a lot!
I tried
flat
with your example and passedInfinity
. What I received is the same array. I believe it doesn't support arrays with complex elements.Waiting for the series now๐
๐
What's the expression of the comment? I didn't see it
In second example it says flatten(test) not arr. Great tut anyway ๐
Thanks ๐ . Edited
Do you think it's better to use this for creating deep copies of one-dimensional arrays than the spread operator?