Last active
August 21, 2018 17:25
-
-
Save jhta/4ff4ffa586d11f8a0c9a69bbddddc997 to your computer and use it in GitHub Desktop.
I have a description
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
/* Write some code, that will flatten an array of arbitrarily | |
nested arrays of integers into a flat array of integers. | |
e.g. [[1,2,[3]],4] -> [1,2,3,4]. */ | |
const flattenArray = array => array.reduce( | |
(acumulator, element) => acumulator.concat( | |
Array.isArray(element) ? | |
flattenArray(element) | |
: | |
element | |
), [] | |
) | |
/* I'm sure that your team have amazing engineers that | |
understand the recursivity and functional javascript + es6. | |
But for the rest of humans, I can explicate it:*/ | |
function flattenArrayForDommies(array) { | |
// first, I'm using the array method reduce. this let me iterate | |
// every item and get an acumulator. We define a the method for generate | |
// this acumulator | |
console.log("recursive itself:" array); | |
return array.reduce(iterate, []); | |
} | |
// reduce method | |
function iterate(acumulator, element) { | |
console.log("current acum:", acumulator); | |
console.log("current element:", element); | |
// if the element is an array, call recursive flatten array method | |
if (Array.isArray(el)) { | |
// if is an array, return the acumulator concat with the recursive call | |
// for the array element | |
return [...acum, ...(flattenArrayForDommies(el))]; // spread operator :D | |
} | |
// if it is not an array, push it in the acumulator | |
return [...acum, (el)]; | |
} | |
console.log("flatten", flattenArray([[1,2,[3]],4])) | |
console.log("flatten", flattenArrayForDommies([[1,2,[3]],4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment