Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function flattenArray(array) {
if (arguments.length === 0) return [];
else return Array.from(flatten(array));
}
// Generator
function *flatten(array) {
// loop each value in the array
for (elt of array)
if (Array.isArray(elt)) yield *flatten(elt); // if value is an array it calls itself and passes in the value
else if (typeof elt === "function") yield elt() // check if the value is a function and returns that functions value
else yield elt; // otherwise just add the value
}
flattenArray([1, "2", [3, function () { return 4; }, [ "five" ], "six", true, { prop: "val" }]]) // [1, "2", 3, 4, "five", "six", true, { prop: "val" }]
flattenArray([1, 2, [3, [4, 5], 6], 7, 8]) // [1, 2, 3, 4, 5, 6, 7, 8]
flattenArray([1, '2', [3, [4], function () { return 'five'; }]]) // [1, '2', 3, 4, 'five']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.