Created
June 22, 2017 00:27
-
-
Save pedrouid/b128bd3604e28ef5281dc560914b83b0 to your computer and use it in GitHub Desktop.
Flatten Arbitrarily Nested Arrays Method (Javascript)
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
// Using recursion this method will concatenate the values of nested arrays into a single array | |
function flatten(arr) { | |
var holder = []; | |
for(var i = 0; i < arr.length; i++) { | |
if(Array.isArray(arr[i])) { | |
holder = holder.concat(flatten(arr[i])); | |
} else { | |
holder.push(arr[i]); | |
} | |
} | |
return holder; | |
} | |
flatten([[1,2,[3]],4]) // [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment