Skip to content

Instantly share code, notes, and snippets.

@johngrant
Created April 11, 2017 17:31
Show Gist options
  • Save johngrant/6a4be5125a0eea3f4253a51327e606c6 to your computer and use it in GitHub Desktop.
Save johngrant/6a4be5125a0eea3f4253a51327e606c6 to your computer and use it in GitHub Desktop.
This snippet of javascript code will flatten an array with nested arrays of any arbitrary depth.
var arr = [1,2,3,[2,[9,9],5],[4,5,5]];
function flatten(input) {
var output = [];
for (var i = 0; i < input.length; i++) {
output = Array.isArray(input[i])
? [...output, ...flatten(input[i])]
: [...output, ...input[i]];
}
return output;
}
console.log(flatten(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment