Last active
September 24, 2016 05:52
-
-
Save alvarolorentedev/b50d3caf958082d283880750d1ce5ec7 to your computer and use it in GitHub Desktop.
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
//implementation | |
/** | |
* @name flatten | |
* @brief flatten an array of arbitrarily nested arrays of integers into a flat array of integers. | |
* @params $array javascript array with no empty arrays allowed | |
* @return flat array of integers | |
* @example [[1,2,[3]],4] -> [1,2,3,4]. | |
*/ | |
function flatten(array){ | |
var result = []; | |
for(var element of array){ | |
if(Array.isArray(element)) | |
result = result.concat(flatten(element)); | |
else | |
result.push(element); | |
} | |
return result; | |
} | |
//Test | |
var nestedData = [[1,2,[3]],4]; | |
var nestedPairsData = [[1,2,[3]],[4,5],3,[1,2],4]; | |
var flatData = [1,2,3,4,5]; | |
console.assert(JSON.stringify(flatten(nestedData)) == '[1,2,3,4]', 'error nestedData'); | |
console.assert(JSON.stringify(flatten(nestedPairsData)) == '[1,2,3,4,5,3,1,2,4]', 'error nestedPairsData'); | |
console.assert(JSON.stringify(flatten(flatData)) == '[1,2,3,4,5]', 'error flatData'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment