Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created November 1, 2016 12:11
Show Gist options
  • Select an option

  • Save gkucmierz/16c5e2b74a1e409884c5d3e7e95563bd to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/16c5e2b74a1e409884c5d3e7e95563bd to your computer and use it in GitHub Desktop.
Flatten array from desired level
// Flatten array from desired level
let flattenArray = function(arr, lvl = 0) {
if (!(arr instanceof Array)) return lvl === 0 ? arr : [arr];
if (lvl > 0) {
return arr.map((el) => flattenArray(el, lvl-1));
} else {
return arr.reduce((arr, el) => {
return arr.concat(flattenArray(el, lvl-1));
}, []);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment