Last active
August 10, 2016 20:57
-
-
Save dperrymorrow/e5078be6a028426e1e22295542c8090b to your computer and use it in GitHub Desktop.
recursive flatten array in Javascript
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
// 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