Skip to content

Instantly share code, notes, and snippets.

@dons20
Last active December 6, 2018 17:46
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 dons20/6e042e21cb161002814aff3bfddd8c8b to your computer and use it in GitHub Desktop.
Save dons20/6e042e21cb161002814aff3bfddd8c8b to your computer and use it in GitHub Desktop.
This code will flatten an array of arbitrarily nested arrays of integers into a flat array of integers
//e.g. [[1,2,[3]],4] -> [1,2,3,4]
let complexArray = [[1,2,[3]],4];
//Legacy Approach
function flatten(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten(complexArray));
//Modern Approach
//let modernFlat = complexArray.flat(Infinity);
//console.log(modernFlat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment