Skip to content

Instantly share code, notes, and snippets.

@ancyrweb
Created January 12, 2022 04:22
Show Gist options
  • Save ancyrweb/9243f6ffbe5bdc5d18d521bce2f17b82 to your computer and use it in GitHub Desktop.
Save ancyrweb/9243f6ffbe5bdc5d18d521bce2f17b82 to your computer and use it in GitHub Desktop.
function flatten(array) {
return array.reduce((previousValue, currentValue) => {
if (Array.isArray(currentValue)) {
// current value is an array, merge values and return the result
return [...previousValue, ...currentValue];
}
// current value is not an array, just add it to the end of the accumulation
return [...previousValue, currentValue];
}, []);
}
const elements = [1, [2], 3, [4, 5], [6]];
const nextElements = flatten(elements); // [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment