Created
October 24, 2017 19:33
-
-
Save farskid/0b47dad0ba5315735ec5421070038df4 to your computer and use it in GitHub Desktop.
Flatten multi-dimensional arrays recursively in Javascript
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 flattenArray(array) { | |
let result = []; | |
array.forEach(function(item, i) { | |
if (Array.isArray(item)) { | |
result = result.concat(flattenArray(array[i])); | |
} | |
else { | |
result = result.concat([item]); | |
} | |
}); | |
return result; | |
} | |
console.log(flattenArray([1,2,[3,[4]], 5])); // [1,2,3,4,5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment