Skip to content

Instantly share code, notes, and snippets.

@ephbaum
Last active June 26, 2016 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ephbaum/0da9a68017d75d9dddce82dfbf96e0fb to your computer and use it in GitHub Desktop.
Save ephbaum/0da9a68017d75d9dddce82dfbf96e0fb to your computer and use it in GitHub Desktop.
/**
* 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