Skip to content

Instantly share code, notes, and snippets.

@gretzky
Created November 27, 2019 23:11
Show Gist options
  • Save gretzky/1c8b8b4a4848d93877e1bf11f695532d to your computer and use it in GitHub Desktop.
Save gretzky/1c8b8b4a4848d93877e1bf11f695532d to your computer and use it in GitHub Desktop.
flatten.js
// this method executes a reducer function on each element of the array
// in this case, if the current value (b) is an array, we recurse through
// and concatenate the nested element to a new, empty array (regardless of how deeply nested it is)
// if the element isn't nested, we simply just add it to the new array
// this approach avoids mutation of the original array
//
// more on .reduce - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
// more on recursion/functional patterns - https://medium.com/dailyjs/functional-js-with-es6-recursive-patterns-b7d0813ef9e3
// even more on recursion - https://marmelab.com/blog/2018/02/12/understanding-recursion.html
const flattenArr = (arr) => arr.reduce(
(accumulator, currentVal) => accumulator.concat(Array.isArray(currentVal) ? flatten(currentVal) : currentVal), []
);
flattenArr([[1,2,[3]],4])
flattenArr([1,[[[2]]],[[[[[3]]]]], 4, [5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment