Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Created January 30, 2018 04:27
Show Gist options
  • Save bozdoz/929c63504d4e0858bbc44f9693a692df to your computer and use it in GitHub Desktop.
Save bozdoz/929c63504d4e0858bbc44f9693a692df to your computer and use it in GitHub Desktop.
Recursively flattens nested arrays
/**
* Recursively flattens nested arrays
* ex: [[1,2,[3]],4] -> [1,2,3,4]
*
* @param Array arr
* @return Array
*/
const flatten = (arr) => (
// reduce will iterate and
// add to an array
arr.reduce((a, b) => (
// concat will join the inner
// arrays to the final array
a.concat(Array.isArray(b) ? flatten(b) : b)
), [])
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment