Flatten Nested Array in JavaScript
ArraysRecursion
Implement a function to flatten a nested array in JavaScript.
Examples
Example 1
Input
flattenArray([1, [2, [3, 4], 5], 6]);Output
[1, 2, 3, 4, 5, 6]Explanation
The function flattens the nested array.
Constraints
- The input is a nested array
- The output is a flattened array
Hints
Editorial: Flatten Nested Array in JavaScript
Solution
We can use a recursive function to flatten the nested array.
Let's discuss the approach in detail.
- We will create a function called
flattenthat will take a value as an argument. - We will check if the value is an array using
Array.isArray(val). - If it is an array, we will iterate over the array and check if the value is an array using
Array.isArray(value). - If it is an array, we will call the
flattenfunction recursively with the value. - If it is not an array, we will push the value to the
valArrarray. - Finally, we will return the
valArrarray.
function flatten(val) { let valArr = []; Array.isArray(val) && val.forEach(value => { if(Array.isArray(value)){ valArr.push(...flatten(value)); } else{ valArr.push(value); } }) return valArr; }
Time Complexity
O(n) where n is the number of elements in the array.
Space Complexity
O(n) for the result array.
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it