Created
July 25, 2016 23:03
-
-
Save d-oliveros/96a2fded89277758fa3f8f0ddf9b1d75 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
/** | |
* Recursively flattens an array. | |
* | |
* @param {Array} arr Array to flatten. | |
* @return {Array} Flattened array. | |
*/ | |
function flatten(arr) { | |
var flattened = []; | |
for (var i = 0, len = arr.length; i < len; i++) { | |
if (Array.isArray(arr[i])) { | |
flattened.push.apply(flattened, flatten(arr[i])); | |
} else { | |
flattened.push(arr[i]); | |
} | |
} | |
return flattened; | |
} | |
console.log(flatten([[1,2,[3]],4])); // [1,2,3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment