Skip to content

Instantly share code, notes, and snippets.

@Zikoel
Created January 26, 2020 11:25
Show Gist options
  • Save Zikoel/8f352ee6c10cbdb252f307e35e4d7ba7 to your computer and use it in GitHub Desktop.
Save Zikoel/8f352ee6c10cbdb252f307e35e4d7ba7 to your computer and use it in GitHub Desktop.
Array flatten js function
// 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