Last active
January 23, 2020 09:57
-
-
Save sunguru98/2f3ba755bc3b3d92b161762ebcf78592 to your computer and use it in GitHub Desktop.
Flatten an array without using flat method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const flattenArray = nestedArr => { | |
// Checking for the emptiness of array | |
if (!nestedArr.length) return null; | |
// Creating a new array for every recursive call | |
const newArr = []; | |
// If the current element is an array, we recursively call the function and then push the values present in the returned array. | |
// Else we just push the current element on to the new Array. | |
nestedArr.forEach(el => | |
Array.isArray(el) ? newArr.push(...flattenArray(el)) : newArr.push(el) | |
); | |
// Finally we return the array to continue the recursion, or exit from the final call stack. | |
return newArr; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment