Skip to content

Instantly share code, notes, and snippets.

@praveenpuglia
Created July 27, 2018 14:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save praveenpuglia/cf3a6c5bf8a9c2d60b6a022729ae6e84 to your computer and use it in GitHub Desktop.
Save praveenpuglia/cf3a6c5bf8a9c2d60b6a022729ae6e84 to your computer and use it in GitHub Desktop.
Deep flatten a JavaScript array using Array.prototype.reduce
function flatten(array) {
return array.reduce( (acc, e) => {
if(Array.isArray(e)) {
// if the element is an array, fall flatten on it again and then take the returned value and concat it.
return acc.concat(flatten(e));
} else {
// otherwise just concat the value.
return acc.concat(e);
}
}, [] ) // initial value for the accumulator is []
};
flatten([1,2,3, [4,5, [6,7,[9,8]]]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment