Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Last active September 28, 2016 21:11
Show Gist options
  • Save christiannwamba/de0d07dc861f3bc98d367c5b9d93beaf to your computer and use it in GitHub Desktop.
Save christiannwamba/de0d07dc861f3bc98d367c5b9d93beaf to your computer and use it in GitHub Desktop.
Flatten nested array with recurssion
// 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