Skip to content

Instantly share code, notes, and snippets.

@mikevercoelen
Created January 8, 2018 15:39
Show Gist options
  • Save mikevercoelen/9e8e66d0e8aee78d8b0cc98e6513c835 to your computer and use it in GitHub Desktop.
Save mikevercoelen/9e8e66d0e8aee78d8b0cc98e6513c835 to your computer and use it in GitHub Desktop.
Flatten a nested array in Javascript
//
// [email protected]
//
// For this solution, when a project has lodash, I would suggest to use `flattenDeep` @ https://lodash.com/docs/4.17.4#flattenDeep
// But ofcourse, a manual util function is easily written:
const nestedArray = [1, [2, 3], [4, 5, [6, 7]], 8]
function flattenArray (nestedArray) {
let flatArray = []
function flatten (array, newArray) {
for (let i = 0; i < array.length; i++) {
if (!Array.isArray(array[i])) {
newArray.push(array[i])
} else {
flatten(array[i], newArray)
}
}
}
flatten(nestedArray, flatArray)
return flatArray
}
const flattenedArray = flattenArray(nestedArray)
console.log(flattenedArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment