Skip to content

Instantly share code, notes, and snippets.

@jackson-dean
Last active June 25, 2016 19:05
Show Gist options
  • Save jackson-dean/bf2f80761a1046246452811e8bda817f to your computer and use it in GitHub Desktop.
Save jackson-dean/bf2f80761a1046246452811e8bda817f to your computer and use it in GitHub Desktop.
Methods for flattening nested array (array of arrays) in JavaScript
//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