Last active
August 9, 2016 01:30
-
-
Save dengjonathan/13aa38f631940a04c1ed7774d68eda4d to your computer and use it in GitHub Desktop.
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
function flatten(array) { | |
var output = []; | |
// iterate through all items in argument array | |
for (var j = 0; j < array.length; j++) { | |
var value = array[j]; | |
// base case: value is not an array, so just push to output | |
if (!Array.isArray(value)) { | |
output.push(value); | |
} else { | |
// recursive case: if value is an array, flatten it to a 1D array. | |
// i.e. [[1]] will become [1] and store the flattened array in original | |
// 'value' variable | |
value = flatten(value); | |
// because value is now a 1D array, you can push each item in it to | |
// output | |
for (var i = 0; i < value.length; i++) { | |
output.push(value[i]); | |
} | |
} | |
} | |
// flatten will always return a 1D array i.e. [1,2,3], which allows us | |
// to recursively call it | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment