Created
April 11, 2017 17:31
-
-
Save johngrant/6a4be5125a0eea3f4253a51327e606c6 to your computer and use it in GitHub Desktop.
This snippet of javascript code will flatten an array with nested arrays of any arbitrary depth.
This file contains 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
var arr = [1,2,3,[2,[9,9],5],[4,5,5]]; | |
function flatten(input) { | |
var output = []; | |
for (var i = 0; i < input.length; i++) { | |
output = Array.isArray(input[i]) | |
? [...output, ...flatten(input[i])] | |
: [...output, ...input[i]]; | |
} | |
return output; | |
} | |
console.log(flatten(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment