Skip to content

Instantly share code, notes, and snippets.

@emiliano1
Created April 18, 2017 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emiliano1/0d45f98bb119c25e9894a3487d65c7bc to your computer and use it in GitHub Desktop.
Save emiliano1/0d45f98bb119c25e9894a3487d65c7bc to your computer and use it in GitHub Desktop.
flattenArray
// 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