Created
January 8, 2018 15:39
-
-
Save mikevercoelen/9e8e66d0e8aee78d8b0cc98e6513c835 to your computer and use it in GitHub Desktop.
Flatten a nested array 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
// | |
// [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