Last active
May 20, 2019 12:37
-
-
Save lovasoa/5b27f1c6c24cf4a43e20b7e2817a7c5b to your computer and use it in GitHub Desktop.
mutable array flatten. An array flattening implementation that does not require more memory than the original deep array.
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
/** | |
* Multi-level array flattening. Takes an array of arbitrarily deep nested arrays, and returns an array of values. | |
* It mutates the original array instead of creating a new one. | |
**/ | |
function flatten(arr) { | |
for (let i = 0, inc=1; i < arr.length; i += inc) { | |
if (Array.isArray(arr[i])) { | |
const flat = flatten(arr[i]); | |
arr.splice(i, 1, ...flat); | |
inc = flat.length; | |
} else { inc = 1; } | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment