Skip to content

Instantly share code, notes, and snippets.

@shadedyin
Created May 1, 2015 20:05
Show Gist options
  • Save shadedyin/fe3954191a975874f442 to your computer and use it in GitHub Desktop.
Save shadedyin/fe3954191a975874f442 to your computer and use it in GitHub Desktop.
function isArray(obj) {
return toString.call(obj) === '[object Array]';
};
function flatten(branch, flat, max, depth) {
flat = flat || [ ]; max = max || 1;
depth = ( depth ? depth + 1 : 1);
for(var i in branch) {
if(isArray(branch[i])) {
if((max < 0) || (depth <= max)) {
flatten(branch[i], flat, max, depth);
} else { flat.push(branch[i]); }
} else { flat.push(branch[i]); }
}
return flat;
};
var test = [ 1, [ 2, [ 3, 4 ], [ 5 ], 6 ], 7 ];
console.log(flatten(test, [ ], -1, -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment