Last active
December 6, 2018 17:46
-
-
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
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
//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