An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
Deep Flatten an Array
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 recursionconst 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(test))// 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.
Original Link: https://dev.to/mukul_singhal/deep-flatten-an-array-5elf
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To