Skip to content

Instantly share code, notes, and snippets.

@altintx
Created March 10, 2016 01:42
Show Gist options
  • Save altintx/a90e57782b9eeec4ddca to your computer and use it in GitHub Desktop.
Save altintx/a90e57782b9eeec4ddca to your computer and use it in GitHub Desktop.
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