Skip to content

Instantly share code, notes, and snippets.

@redmundas
Created August 1, 2017 05:14
Show Gist options
  • Save redmundas/2dcce6931cfc2943b2fa530ae0189b56 to your computer and use it in GitHub Desktop.
Save redmundas/2dcce6931cfc2943b2fa530ae0189b56 to your computer and use it in GitHub Desktop.
Demonstrate implementation of Array.flatten in javascript
function flattenRecursive(nested) {
return nested.reduce((flat, item) =>
flat.concat(Array.isArray(item) ? flatten(item) : item)
, [])
}
function flattenIterative(nested) {
let i = 0,
flat = nested.slice() // copy array
while (i < flat.length) {
// continue untill current item is no longer an array
if (Array.isArray(flat[i])) {
// modify array by extracting current item into it
flat.splice(i, 1, ...flat[i])
} else {
i++
}
}
return flat
}
// default implementation is recursive
const flatten = (array, iterative) =>
iterative ? flattenIterative(array) : flattenRecursive(array)
const test = [[[[1]],2,[3,4]],5,[]]
const expected = JSON.stringify([1,2,3,4,5])
console.assert(JSON.stringify(flatten(test)) === expected)
console.assert(JSON.stringify(flatten(test, true)) === expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment