Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active May 20, 2019 12:37
Show Gist options
  • Save lovasoa/5b27f1c6c24cf4a43e20b7e2817a7c5b to your computer and use it in GitHub Desktop.
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.
/**
* 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