Last active
September 28, 2016 21:11
-
-
Save christiannwamba/de0d07dc861f3bc98d367c5b9d93beaf to your computer and use it in GitHub Desktop.
Flatten nested array with recurssion
This file contains 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
// Demo: http://jsbin.com/qaxurogowe/edit?html,js,console,output | |
// Recursive function | |
// which will continue to | |
// iterate through nested array until flattened | |
function flatten() { | |
// A control variable | |
// to hold flattened array | |
var flat = []; | |
// Begin a loop | |
for (var i = 0; i < arguments.length; i++) { | |
var el = arguments[i]; | |
if (el instanceof Array) { | |
// If the element is of type Array | |
// flatten and push to flat | |
flat.push.apply(flat, flatten.apply(this, el)); | |
} else { | |
// if not of type Array | |
// just push the item | |
flat.push(arguments[i]); | |
} | |
} | |
// Returned flattened array | |
return flat; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment