Skip to content

Instantly share code, notes, and snippets.

@sardell
Created August 1, 2016 19:33
Show Gist options
  • Save sardell/dd57124bccb0d7fb2cca8420b786c810 to your computer and use it in GitHub Desktop.
Save sardell/dd57124bccb0d7fb2cca8420b786c810 to your computer and use it in GitHub Desktop.
Flatten Nested Array with ES2015
// This example uses ES2015 features. Use Babel to compile down to JS, or see the example at http://codepen.io/sardell/pen/VjGYRz
// example array provided
var example = [[1,2,[3]],4];
function flatten_array(nested) {
// concatenate using the spread operator
const flat = [].concat(...nested)
// repeat flatten_array function until nested array is flat
return flat.some(Array.isArray) ? flatten_array(flat) : flat;
}
console.log(flatten_array(example));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment