Skip to content

Instantly share code, notes, and snippets.

@7cc
Last active January 5, 2019 10:51
Show Gist options
  • Select an option

  • Save 7cc/90614780af8dea8917e0c548dbcc376a to your computer and use it in GitHub Desktop.

Select an option

Save 7cc/90614780af8dea8917e0c548dbcc376a to your computer and use it in GitHub Desktop.
recursive, call outer vs inner function
var array = [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]
// call outer function
function flatten(array) {
return array.reduce((prev, cur)=> {
return Array.isArray(cur)
? [...prev, ...flatten(cur)]
: [...prev, cur]
}, [])
}
// call inner function
function flatten(array) {
return array.reduce(function inner(prev, cur) {
return Array.isArray(cur)
? [...cur.reduce(inner, prev)]
: [...prev, cur]
}, [])
}
flatten(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment