Last active
August 9, 2018 10:17
-
-
Save manojVivek/06bf6e339489878055fd0b3d86b2cc16 to your computer and use it in GitHub Desktop.
Code snippet to flatten a nested 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
//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