Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active January 26, 2019 17:29
Show Gist options
  • Save crshmk/90b2ccb323c462c1d21fe14ebe977809 to your computer and use it in GitHub Desktop.
Save crshmk/90b2ccb323c462c1d21fe14ebe977809 to your computer and use it in GitHub Desktop.
Flatten array
/**
* @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