Last active
June 26, 2016 14:24
-
-
Save ephbaum/0da9a68017d75d9dddce82dfbf96e0fb 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
/** | |
* Resursively flattens an Array of depth n | |
* | |
* @param aSrc Array to be flattened | |
* @returns Array Single depth array | |
*/ | |
var flatten = function(aSrc) { | |
if (Array.isArray(aSrc) && aSrc.length > 0) { // Test that paramater is both array and non-zero length | |
var head = aSrc[0], // Get first element from paramater | |
tail = aSrc.slice(1); // Get the rest of array after first element | |
return flatten(head).concat(flatten(tail)); // Continue flattening, start with first elem and add remainder | |
} else { // Parameter is not array, add to new array and return | |
return [].concat(aSrc); | |
} | |
}; | |
// flatten([1,2,[3,[4]],5,[[[6]]]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment