Last active
April 21, 2019 04:59
-
-
Save m1m6/df7778e0437a1ead5ae54f7ad9bc200d to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
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 flatArray(arrayToBeFlatted, output) { | |
if (!arrayToBeFlatted){ | |
throw new Error('Please provide valid array') | |
} | |
if (!output) { | |
output = []; | |
} | |
for (let i = 0; i < arrayToBeFlatted.length; i++) { | |
const currentArrayItem = arrayToBeFlatted[i] | |
if (Array.isArray(currentArrayItem)) { | |
flatArray(currentArrayItem, output); | |
} else { | |
output.push(currentArrayItem); | |
} | |
} | |
return output; | |
} | |
console.log(flatArray([[1, 2, [3]], 4])); | |
console.log(flatArray([[1], [2, 3]])); | |
console.log(flatArray([[1], [2, 3], [4]])); | |
console.log(flatArray([[[1, [1]], 2, 3], [4, 5]])); | |
console.log(flatArray([[1, 2, 3], [4, 5]])) | |
console.log(flatArray(undefined)) | |
console.log(flatArray(null)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment