Created
August 1, 2017 05:14
-
-
Save redmundas/2dcce6931cfc2943b2fa530ae0189b56 to your computer and use it in GitHub Desktop.
Demonstrate implementation of Array.flatten in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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