Last active
August 14, 2017 13:55
-
-
Save jkruse14/7348f1d9139fec0306ae0af7d04cbdb5 to your computer and use it in GitHub Desktop.
Flatten an array
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
//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