Created
July 27, 2018 14:37
-
-
Save praveenpuglia/cf3a6c5bf8a9c2d60b6a022729ae6e84 to your computer and use it in GitHub Desktop.
Deep flatten a JavaScript array using Array.prototype.reduce
This file contains hidden or 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
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