Last active
June 29, 2016 12:55
-
-
Save stephenwil/71449903280349867308037515dd6cc4 to your computer and use it in GitHub Desktop.
Flatten an 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
//Write some code, that will flatten an array of arbitrarily nested arrays of //integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
// This solution makes use of .toString() to flatten the array, whereas if the requirements also included flattening object structures, then the typical approach of having a recursing function would be used. | |
var testData = { | |
srcArray1 : [[1,2,[3]],4,[5]], | |
srcArray2 : [[[1],2],[[3]],4], | |
srcArray3 : [0,[1,1],[[2,2,2,2],[[1],[[2]],[[[3],2]]]]], | |
srcArray4 : [1,[2],[[3]],[[[4]]]] | |
}; | |
var outputText = ""; | |
for (data in testData) { | |
outputText += JSON.parse('['+testData[data].toString()+']')+'\n'; | |
} | |
console.log(outputText); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment