Created
January 26, 2020 11:25
-
-
Save Zikoel/8f352ee6c10cbdb252f307e35e4d7ba7 to your computer and use it in GitHub Desktop.
Array flatten js function
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
// Of course we can use something like this [lodash flattenDeep](https://lodash.com/docs/4.17.15#flattenDeep) | |
// but here we want our solution | |
const nestedArray = [[1,2,[3]],4] | |
const moreNestedArray = [1,2,[[[5, 6, [8, [9], [10]]]]]] | |
const flat = array => { | |
return array.reduce( (acc, cur) => | |
typeof cur === 'number' | |
? [...acc, cur] | |
: [...acc, ...flat(cur)] | |
, [] ) | |
} | |
console.log( flat(nestedArray) ) | |
console.log( flat(moreNestedArray) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment