Skip to content

Instantly share code, notes, and snippets.

@narenderv7
Created December 25, 2019 08:54
Show Gist options
  • Save narenderv7/1a47b9c96a8f42344eb4b412e90e955f to your computer and use it in GitHub Desktop.
Save narenderv7/1a47b9c96a8f42344eb4b412e90e955f to your computer and use it in GitHub Desktop.
Flattens Array
function* flatten(array, deep) {
if (deep === undefined) deep = 1
for (const item of array) {
if (Array.isArray(item) && deep > 0) {
yield* flatten(item, deep - 1)
} else {
yield item
}
}
}
// use case
const array = [[1,2,[3]],4]
const flattened = [...flatten(array, Infinity)] // Used Infinity, as if you're unsure of the depth (nested arrays)
console.log(flattened) // results [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment