Skip to content

Instantly share code, notes, and snippets.

@christ776
Created February 3, 2020 20:48
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 christ776/0698b43fc509d77eefcd07660604fe01 to your computer and use it in GitHub Desktop.
Save christ776/0698b43fc509d77eefcd07660604fe01 to your computer and use it in GitHub Desktop.
function flattenArray(arr) {
if (arr === undefined || arr === null) {
throw new Error('Bad argument type:', arr);
}
const flattenedArray = [].concat(...arr)
for(const m of flattenedArray) {
if (m instanceof Array) {
return flattenArray(flattenedArray);
}
}
return flattenedArray;
}
// === Some test cases =====
// Complex case 1
console.log(flattenArray([[1,2,[3]],4]));
// Complex case 2
console.log(flattenArray([[1,2,[3]],4, [[[5]]]]));
// The empty array
console.log(flattenArray([]));
// Passing undefined as arg
console.log(flattenArray(undefined));
//Passing null
console.log(flattenArray(null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment