Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.