Skip to content

Instantly share code, notes, and snippets.

@BenShelton
Created February 23, 2017 16:50
Show Gist options
  • Save BenShelton/7741256a83d826a1164412303c388622 to your computer and use it in GitHub Desktop.
Save BenShelton/7741256a83d826a1164412303c388622 to your computer and use it in GitHub Desktop.
Flatten a Nested Array
/* 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