Created
April 18, 2017 15:30
-
-
Save emiliano1/0d45f98bb119c25e9894a3487d65c7bc to your computer and use it in GitHub Desktop.
flattenArray
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
// recursive function to flatten an n-level deep array | |
function flattenArray(array, result = []) { | |
var arrayLength = array.length; | |
for (var i = 0; i < arrayLength; i++){ | |
if (array[i] instanceof Array) { | |
// if item is an Array, call the function recursevely | |
result.concat(flattenArray(array[i], result)); | |
} else { | |
// if item is not an Array, simply add it to final result | |
result.push(array[i]); | |
} | |
} | |
return result; | |
} | |
// support function to test the results | |
function test(input, expectedOutput) { | |
var result = flattenArray(input); | |
if (result.length !== expectedOutput.length) { | |
throw "Expected: " + expectedOutput + ". Actual result: " + result; | |
} | |
for (var i = 0, l = result.length; i < l; i++) { | |
if (result[i] !== expectedOutput[i]) { | |
throw "Expected: " + expectedOutput + ". Actual result: " + result; | |
} | |
} | |
return true; | |
} | |
test([], []); | |
test( | |
[1, [2], 3], | |
[1, 2, 3] | |
); | |
test( | |
[[1, 2], 3], | |
[1, 2, 3] | |
); | |
test( | |
[[[1], 2], 3], | |
[1, 2, 3] | |
); | |
test( | |
[[[[1]], 2], 3], | |
[1, 2, 3] | |
); | |
test( | |
[[1], [2], [3]], | |
[1, 2, 3] | |
); | |
test( | |
[[[[1], [2]], [3]]], | |
[1, 2, 3] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment