Last active
January 26, 2019 17:29
-
-
Save crshmk/90b2ccb323c462c1d21fe14ebe977809 to your computer and use it in GitHub Desktop.
Flatten array
This file contains hidden or 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
/** | |
* @param xs array | |
* @param oneLevel boolean -> pass true to flatten only one level | |
*/ | |
let flatten = (xs, oneLevel) => | |
oneLevel ? xs.reduce( (acc, xs) => acc.concat(xs), []) : | |
xs.reduce( (acc, x) => Array.isArray(x) ? acc.concat(flatten(x)) : acc.concat(x), []); | |
let nums = [1, [2, [3, 4, [5] ]]] | |
flatten(nums) | |
// -> [1, 2, 3, 4, 5] | |
// flatten one level deep | |
nums = [1, [2, [3, 4] ], 5] | |
flatten(nums, true) | |
// -> [1, 2, [3, 4], 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment