Skip to content

Instantly share code, notes, and snippets.

@mikedoubintchik
Last active July 17, 2019 16:49
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 mikedoubintchik/ee6bdedc867d537d7d2b5b5d45ce39d1 to your computer and use it in GitHub Desktop.
Save mikedoubintchik/ee6bdedc867d537d7d2b5b5d45ce39d1 to your computer and use it in GitHub Desktop.
// original array
var array = [[1,2,[3]],4];
/**
* Flatten function for arrays with unlimited depth
*/
const flatten = array => {
// if input is not array, throw error
if (!Array.isArray(array)) throw (new Error('This function can only be used on arrays'));
// loop through array
while (array.find(el => Array.isArray(el))) array = Array.prototype.concat(...array);
return array
}
console.log(flatten(arr)); // should return => [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment