Skip to content

Instantly share code, notes, and snippets.

@missett
Created December 10, 2013 10:26
Show Gist options
  • Save missett/7888569 to your computer and use it in GitHub Desktop.
Save missett/7888569 to your computer and use it in GitHub Desktop.
Recursive implementation to flatten a nested array structure.
var flatten = function(nested) {
var head = nested.slice(0, 1),
tail = nested.slice(1),
type = Object.prototype.toString.call(head[0]);
if(nested.length === 0) return [];
if(type === '[object Array]') return flatten(head[0]).concat(tail);
return head.concat(flatten(tail));
};
var test = ['a', 'b', ['c', 'd'], 'e', 'f'];
console.log(flatten(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment