Skip to content

Instantly share code, notes, and snippets.

@m1m6
Last active April 21, 2019 04:59
Show Gist options
  • Save m1m6/df7778e0437a1ead5ae54f7ad9bc200d to your computer and use it in GitHub Desktop.
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
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