Skip to content

Instantly share code, notes, and snippets.

@kra3
Created Oct 29, 2017
Embed
What would you like to do?
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