Created
March 10, 2016 01:42
-
-
Save altintx/a90e57782b9eeec4ddca 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 flatten(input) { console.log(input); | |
var _flatten = (input, output) => { | |
console.debug("flattening %o", input); | |
return input.reduce((output, item) => { | |
if (typeof item == "object" && item instanceof Array) { | |
console.debug("flattening nested array %o", item); | |
return _flatten(item, output); | |
} else { | |
output.push(item); | |
return output; | |
} | |
}, output); | |
} | |
return _flatten(input, []); | |
} | |
flatten([[[[1,2],3],[],4,[5,6],7,8,9]]); // [1 2 3 4 5 6 7 8 9] | |
flatten([{ 0: "not an array", length: 1}, 1, 2]); // [{ 0: "not an array", length: 1}, 1, 2] | |
flatten(0, 1, [2, 3]); // Error: input is not an array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment