Skip to content

Instantly share code, notes, and snippets.

@gugadev
Created January 21, 2020 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gugadev/aa9357d72396d5b69a614828a4a28a2e to your computer and use it in GitHub Desktop.
Save gugadev/aa9357d72396d5b69a614828a4a28a2e to your computer and use it in GitHub Desktop.
Flatten an array with n deep levels.
const source = [[1, 2, [3, [4]]], 5]
const flatArray = (src) => {
const flattened = []
function isArray(value) {
return value instanceof Array
}
// do not modify the original array, instead, clone it
function flat(arr = [...src], index = 0) {
const currentValue = arr[index]
// there are no more elements...
if (!currentValue) {
// if there are some inner array yet...
if (flattened.some(v => v instanceof Array)) {
const newSrc = [...flattened] // will be our new source array
flattened.splice(0, flattened.length) // empty the array to start again
return flat(newSrc, 0)
}
// otherwise, return it
return flattened
}
// if the current value is an inner array, just spread it ;)
if (isArray(currentValue)) {
flattened.push(...currentValue)
} else { // else, just add it
flattened.push(currentValue)
}
// next iteration
return flat(arr, index + 1)
}
return flat()
}
const original = source
const flattened = flatArray(source)
console.log('Original array:', original) // [[1, 2, [3, [4]]], 5]
console.log('Flattened array:', flattened) // [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment