Created
December 12, 2016 19:27
-
-
Save lsmoura/fbd8d955072a38d9ffc1ff7678787b57 to your computer and use it in GitHub Desktop.
Javascript flatten
This file contains hidden or 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
// Flatten an array with possible nested array into a single array | |
function flatten(arr) { | |
if (!Array.isArray(arr)) | |
// Do nothing if we're not an array | |
return(arr); | |
var ret = []; | |
var i, j; | |
for (i = 0; i < arr.length; i++) { | |
// Flatten each individual element | |
var aux = flatten(arr[i]); | |
if (Array.isArray(aux)) | |
// If we're an array, push each element into our return array | |
for (j = 0; j < aux.length; j++) | |
ret.push(aux[j]); | |
else | |
// If we're not an array, just push the element to the return array | |
ret.push(aux); | |
} | |
return(ret); | |
} | |
/* Some testing cases: | |
console.log(flatten([[1, 2, [3]], 4])); // Expect [1, 2, 3, 4] | |
console.log(flatten([[[[[ 5 ]]]]])); // Expect [5] | |
console.log(flatten([1, 2, 3, 4])); // Expect [1, 2, 3, 4] | |
console.log(flatten([[1,2],[3,4]])); // Expect [1, 2, 3, 4] | |
console.log(flatten([[1,2],[3,4], [[5,6],[7,8]]])); // Expect [1, 2, 3, 4, 5, 6, 7, 8] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment