Skip to content

Instantly share code, notes, and snippets.

@dperrymorrow
Last active August 10, 2016 20:57
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 dperrymorrow/e5078be6a028426e1e22295542c8090b to your computer and use it in GitHub Desktop.
Save dperrymorrow/e5078be6a028426e1e22295542c8090b to your computer and use it in GitHub Desktop.
recursive flatten array in Javascript
// see this javascript working at http://jsbin.com/mehemepume/edit?js,console
// the function calls itself recursivly, so there can be any level of nesting and it will still flatten.
var nested = [[1, 2, [3]], 4],
nestedDeep = [1, 2, 3, [4, 5, 6, [[7, [8]], 9, 10]]];
function flatten(arr) {
var flat = [];
arr.forEach(function (item) {
if (Array.isArray(item)) {
// recursive, will work with any level of nesting
flatten(item).forEach(function (child) {
return flat.push(child);
});
} else {
flat.push(item);
}
});
return flat;
}
console.log(JSON.stringify(flatten(nested)));
// [1,2,3,4]
console.log(JSON.stringify(flatten(nestedDeep)));
// [1,2,3,4,5,6,7,8,9,10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment