Last active
July 8, 2019 07:02
-
-
Save JiriChara/754a718ce14882c91ea957b77898cab2 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((acc, current) => { | |
// if current element is an array call flatten method recursively | |
if (Array.isArray(current)) { | |
return acc.concat(flatten(current)); | |
} | |
// otherwise just accumulate the current array | |
return acc.concat(current); | |
}, []); | |
}; | |
// Test | |
const deepArray = [[1], [2, 3, [4]], 5]; | |
console.assert(JSON.stringify(flatten(deepArray)) === JSON.stringify([1, 2, 3, 4, 5])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment