Last active
December 4, 2017 19:18
-
-
Save robbieferrero/ec2f5e7e500db52ccd8a0e4c2c372b4a to your computer and use it in GitHub Desktop.
Deep Flatten
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
/** | |
* A utility function to flatten an array, nested to any depth. | |
* @param {Array} initialArray | |
* | |
*/ | |
function deepFlatten(initialArray) { | |
return initialArray.reduce((acc, v) => { | |
return acc.concat(Array.isArray(v) ? deepFlatten(v) : v); | |
}, []); | |
} | |
/** | |
* Example usage | |
*/ | |
// Example array | |
const test = [[1, 2, [3]], 4]; | |
console.log(deepFlatten(test)); | |
// [1,2,3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment