Created
December 25, 2019 08:54
-
-
Save narenderv7/1a47b9c96a8f42344eb4b412e90e955f to your computer and use it in GitHub Desktop.
Flattens Array
This file contains 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, 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