Created
January 5, 2018 17:05
-
-
Save robertovg/b0cea85f352f506e4eac3b72e3b5360c to your computer and use it in GitHub Desktop.
Function to flat arrays
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
// const a = [1, [], [2, 3, [4], | |
// [5], | |
// [1, 2, 3, 4, [5, [6], | |
// [4], [], | |
// ]] | |
// ], 3, 6]; | |
// const b = [1, 2, 3]; | |
/** | |
* Function to flat arrays | |
*/ | |
function flatArray(array = []) { | |
// We reduce the original array to a flat new array | |
return array.reduce( | |
(acu, curr) => | |
// If the current element is not array | |
(!Array.isArray(curr) ? | |
// Then just continue adding elements to our array | |
[...acu, curr] : | |
// If it's an array, we just flat this position of the array | |
[...acu, ...flatArray(curr)]) | |
, [] | |
); | |
} | |
// console.log(a); | |
// console.log(flatArray(a)); | |
// console.log('-'); | |
// console.log(b); | |
// console.log(flatArray(b)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment