Created
October 29, 2017 22:30
-
-
Save kra3/820f45d47f7babe103f044bb04ac18c6 to your computer and use it in GitHub Desktop.
flatten an arbitrarily nested 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
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