Created
August 24, 2017 04:54
-
-
Save arfianadam/ca2fc81603c35c9116dcc78e2a151d50 to your computer and use it in GitHub Desktop.
flatten nested array using 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
const flatten = function(array, flattenArray = []) { | |
for (let i = 0; i < array.length; i++) { | |
const value = array[i]; | |
if (Array.isArray(value)) { | |
flatten(value, flattenArray); | |
} else { | |
flattenArray.push(value); | |
} | |
} | |
return flattenArray; | |
}; | |
const a = [1, [2, [3, 4, [5, [6, 7]]]], 8, 9]; | |
console.log(flatten(a)); // [1, 2, 3, 4, 5, 6, 7, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment