Created
August 1, 2016 19:33
-
-
Save sardell/dd57124bccb0d7fb2cca8420b786c810 to your computer and use it in GitHub Desktop.
Flatten Nested Array with ES2015
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
// 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