Last active
March 23, 2018 15:02
-
-
Save dana-ross/8894dcd8cb6c8de1a341c5fd73d6f44f to your computer and use it in GitHub Desktop.
The world needed another JavasScript array flattening function
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
/** | |
* Flatten a JavaScript array | |
* @param {Array} arr Array to flatten | |
* @param {number} depth Levels deep to flatten | |
* @return Array | |
*/ | |
export default function flatten(arr, depth = 1) { | |
if(depth === 0) return arr | |
let newArr = [] | |
arr.forEach((x) => { | |
newArr = newArr.concat(x instanceof Array ? flatten(x, depth - 1) : [x]) | |
}) | |
return newArr | |
} |
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
{ | |
"name": "dmrflatten", | |
"version": "0.1.1", | |
"main": "dmrflatten.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment