Skip to content

Instantly share code, notes, and snippets.

@jkruse14
Last active August 14, 2017 13:55
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 jkruse14/7348f1d9139fec0306ae0af7d04cbdb5 to your computer and use it in GitHub Desktop.
Save jkruse14/7348f1d9139fec0306ae0af7d04cbdb5 to your computer and use it in GitHub Desktop.
Flatten an array
//flattens an array of arbitrarily nested arrays without the use of Array.prototype.reduce
//i.e. [1,[2,[3,4]]] => [1,2,3,4]
//returns -1 if input is not an array
function flatten(arr) {
if(!Array.isArray(arr)) {
return -1;
}
let flat = [];
for(let i = 0; i < arr.length; i++) {
let curr = arr[i];
if(Array.isArray(arr[i])) {
curr = flatten(curr);
}
flat = flat.concat(curr);
}
return flat;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment