Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. /*
  2. Flattens an array, e.g. [[1,2,[3]],4] -> [1,2,3,4]
  3.  
  4. Using Array.prototype.reduce() as a functional alternative to a for loop and
  5. relying on recursion to handle nesting.
  6.  
  7. For those unfamiliar, the first argument to reduce() is a function to run for
  8. every item of the array and the second argument is the initial value that we
  9. want to add to, which will eventually be our result. In this case we start with
  10. an empty array and add each nested item to it.
  11. */
  12.  
  13. const flatten = nestedArray =>
  14. nestedArray.reduce((flatArray, currentValue) => {
  15. if (Array.isArray(currentValue))
  16. flatArray.push(...flatten(currentValue));
  17. else
  18. flatArray.push(currentValue);
  19. return flatArray;
  20. },
  21. []);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement