Flatten array in Javascript
- Get link
- X
- Other Apps
In this post, we will see how we can flatten an array in Javascript. This was asked to me in an interview.
Problem Statement:
Input array:
Expected Output:
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
Approach 1: Using Array.flat()
Use the Array.flat() method to get the desired output.
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
We will use "Infinity" as the depth so that it will merge all the nested elements. Refer below screenshot for the output.
But what if you are not allowed to use the inbuilt method in the interview. We can use something like approach 2 for that.
Approach 2: Without Array.flat()
we can use a recursive function. It will have a for each method that will act on each element of the parent array and if the element is found to be a nested array then it will call the recursive function again but now only with the subarray element. I have added below code as an example to show how it can be achieved:
- Get link
- X
- Other Apps
Comments
Post a Comment