Skip to content

Instantly share code, notes, and snippets.

@farskid
Created October 24, 2017 19:33
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 farskid/0b47dad0ba5315735ec5421070038df4 to your computer and use it in GitHub Desktop.
Save farskid/0b47dad0ba5315735ec5421070038df4 to your computer and use it in GitHub Desktop.
Flatten multi-dimensional arrays recursively in Javascript
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