Skip to content

Instantly share code, notes, and snippets.

@jovey-zheng
Last active May 6, 2019 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jovey-zheng/4f58f65e37c2e28910e653485eb2e87c to your computer and use it in GitHub Desktop.
Save jovey-zheng/4f58f65e37c2e28910e653485eb2e87c to your computer and use it in GitHub Desktop.
Flatten deep nested arrays.
// array flatten function
function flatten (arr) {
let result = [].slice.call(arguments)[1] || []
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr[i], result)
} else {
result.push(arr[i])
}
}
return result
}
// invoke: flatten([1, 2, [3, 4, [{num: 5}, {num: 6}]]])
// output: [1, 2, 3, 4, {num: 5}, {num: 6}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment