Skip to content

Instantly share code, notes, and snippets.

@jovey-zheng jovey-zheng/flatten.js
Last active May 6, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.