Created
January 12, 2022 04:22
-
-
Save ancyrweb/9243f6ffbe5bdc5d18d521bce2f17b82 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(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