Skip to content

Instantly share code, notes, and snippets.

@manojVivek
Last active August 9, 2018 10:17
Show Gist options
  • Save manojVivek/06bf6e339489878055fd0b3d86b2cc16 to your computer and use it in GitHub Desktop.
Save manojVivek/06bf6e339489878055fd0b3d86b2cc16 to your computer and use it in GitHub Desktop.
Code snippet to flatten a nested array
//A recurse function to flatten a nested array
function flatten(input, output = []) {
input && input.forEach(element => {
if (element instanceof Array) {
//if found a array flatten it recursively
return flatten(element, output);
}
//if non-array element add it the output
output.push(element);
});
return output;
}
function testFlatten() {
if(!(JSON.stringify(flatten()) == JSON.stringify([]))) throw "Test case null fail";
if(!(JSON.stringify(flatten([[1, 2, [3]], 4])) == JSON.stringify([1, 2, 3, 4]))) throw "Test case 1 fail";
}
testFlatten();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment