Skip to content

Instantly share code, notes, and snippets.

@pedrouid
Created June 22, 2017 00:27
Show Gist options
  • Save pedrouid/b128bd3604e28ef5281dc560914b83b0 to your computer and use it in GitHub Desktop.
Save pedrouid/b128bd3604e28ef5281dc560914b83b0 to your computer and use it in GitHub Desktop.
Flatten Arbitrarily Nested Arrays Method (Javascript)
// Using recursion this method will concatenate the values of nested arrays into a single array
function flatten(arr) {
var holder = [];
for(var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
holder = holder.concat(flatten(arr[i]));
} else {
holder.push(arr[i]);
}
}
return holder;
}
flatten([[1,2,[3]],4]) // [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment