Created
January 21, 2020 18:03
-
-
Save gugadev/aa9357d72396d5b69a614828a4a28a2e to your computer and use it in GitHub Desktop.
Flatten an array with n deep levels.
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
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