Last active
July 17, 2019 16:49
-
-
Save mikedoubintchik/ee6bdedc867d537d7d2b5b5d45ce39d1 to your computer and use it in GitHub Desktop.
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
// 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