Skip to content

Instantly share code, notes, and snippets.

@arbitrary-dev
Last active January 10, 2017 03:55
Show Gist options
  • Save arbitrary-dev/fff9614c4d1f732a41e324b5e5c4a437 to your computer and use it in GitHub Desktop.
Save arbitrary-dev/fff9614c4d1f732a41e324b5e5c4a437 to your computer and use it in GitHub Desktop.
Some code, that will flatten an array of arbitrarily nested arrays
// ECMAScript 6
const flatten = (arr) =>
// Reducer concat array items to accumulated result
// or recursively calls flatten again if the item is an array.
arr.reduce((acc, item) =>
acc.concat(Array.isArray(item) ? flatten(item) // recursively flatten nested array
: item), // concat ordinary item
[]); // init empty accumulator
console.log(flatten( [[1,2,[3]],4] ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment