Last active
June 25, 2016 19:05
-
-
Save jackson-dean/bf2f80761a1046246452811e8bda817f to your computer and use it in GitHub Desktop.
Methods for flattening nested array (array of arrays) in JavaScript
This file contains hidden or 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
//Classic recursive array walk algorithm | |
var flatten = function(nestedArray, output) { | |
output = output || []; | |
var i = 0; | |
for (;i < nestedArray.length; i++) { | |
if (nestedArray[i] instanceof Array) { | |
flatten(nestedArray[i], output); | |
} else { | |
output.push(nestedArray[i]); | |
} | |
} | |
return output; | |
} | |
//Using newer array methods (reduce, some, isArray) | |
var flattenReduce = function(nestedArray) { | |
return nestedArray.reduce(function(previous, current) { | |
return previous.concat(Array.isArray(current) && current.some(Array.isArray) ? flattenReduce(current) : current); | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment