Created
January 18, 2018 16:45
-
-
Save bfillmer/ebddeb42c1eeba5ab4fa2fd830181188 to your computer and use it in GitHub Desktop.
Recursively Flatten an Array
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
// Expected input -> output | |
// [[1,2,[3]],4] -> [1,2,3,4] | |
const input = [[1,2,[3]],4] | |
const flatten = (array, base = []) => array.reduce( | |
(result, current) => ((Array.isArray(current)) ? flatten(current, result) : [...result, current]) | |
, base) | |
// -> [1, 2, 3, 4] | |
console.log(flatten(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment