Created
February 23, 2017 16:50
-
-
Save BenShelton/7741256a83d826a1164412303c388622 to your computer and use it in GitHub Desktop.
Flatten a Nested 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
/* flatten function | |
Accepts an n-dimensional array | |
as an argument and returns a | |
1-dimensional array | |
Returns value for non-arrays | |
Uses recursion to drill down | |
into each array section | |
*/ | |
function flatten(val) { | |
// if not an array returns value | |
if (!(Array.isArray(val))) return val; | |
// call reduce starting with an empty array | |
return val.reduce((acc, curr) => { | |
// recursive flattening of each element | |
return acc.concat(flatten(curr)); | |
}, []); | |
} | |
// testing | |
//console.log(flatten([[1,2,[3]],4]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment