Skip to content

Instantly share code, notes, and snippets.

@kra3
Created October 29, 2017 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kra3/820f45d47f7babe103f044bb04ac18c6 to your computer and use it in GitHub Desktop.
Save kra3/820f45d47f7babe103f044bb04ac18c6 to your computer and use it in GitHub Desktop.
flatten an arbitrarily nested array
const flatten = (arr) => {
const _helper = (arr) => arr.reduce(
(acc, itm) => Array.isArray(itm) ? [...acc, ..._helper(itm)] : [...acc, itm], []);
return _helper(arr);
}
// upgrade to old version https://gist.github.com/kra3/f802061437e3efe062ab2d4c047fe7c0
// still, I advocate to use underscore, lodash or ramda ;) they are more battle tested
console.log(flatten([[1,2,[3]],4]));
console.log(flatten([1, [2, [3, 4]]]).length === 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment