Skip to content

Instantly share code, notes, and snippets.

@gusaiani
Last active July 4, 2018 17:09
Show Gist options
  • Save gusaiani/f4e95f9bff9f905a811705afb43aa181 to your computer and use it in GitHub Desktop.
Save gusaiani/f4e95f9bff9f905a811705afb43aa181 to your computer and use it in GitHub Desktop.
The ES6 function below flattens an arbitrarily deep array.
function flattenArbitrarilyDeepArray(arr, cache = []) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc.concat(flattenArbitrarilyDeepArray(item, acc))
}
else acc.push(item)
return acc
}, cache)
}
flattenArbitrarilyDeepArray([[1,2,[3]],4]) // [1, 2, 3, 4]
flattenArbitrarilyDeepArray([[1,2,[3]],4, [5, [6, [7, 8]]]]) // [1, 2, 3, 4, 5, 6, 7, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment