Created
July 16, 2016 01:23
-
-
Save fadils/7025f69bc0358b8644fb32a0ec37aa21 to your computer and use it in GitHub Desktop.
Flatten Array
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) { | |
return flat(array, []); | |
} | |
function flat(array, result) { | |
for (var i = 0; i < array.length; i++) { | |
var current = array[i]; | |
if (Array.isArray(current)) { | |
flat(current, result); | |
} else { | |
result.push(current); | |
} | |
} | |
return result; | |
} | |
/*console.log('Testing arrays\n'); | |
var array = [1,2,3,4]; | |
console.log('array ' + JSON.stringify(array)); | |
console.log('flattened to ' + JSON.stringify(flatten(array)) ); | |
console.log('---------------'); | |
var array2 = [1,[2,3,[4]]]; | |
console.log('array ' + JSON.stringify(array2) ); | |
console.log('flattened to ' + JSON.stringify(flatten(array2)) );*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment