Skip to content

Instantly share code, notes, and snippets.

@alvarolorentedev
Last active September 24, 2016 05:52
Show Gist options
  • Save alvarolorentedev/b50d3caf958082d283880750d1ce5ec7 to your computer and use it in GitHub Desktop.
Save alvarolorentedev/b50d3caf958082d283880750d1ce5ec7 to your computer and use it in GitHub Desktop.
//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