Created
May 1, 2015 20:05
-
-
Save shadedyin/fe3954191a975874f442 to your computer and use it in GitHub Desktop.
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
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