Guest User

Untitled

a guest
Nov 18th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.63 KB | None | 0 0
  1. const flatten = (array) => {
  2. // Concat nested arrays recursively
  3. const f = (arr, acc) => {
  4. if(arr.length > 0) {
  5. const first = arr[0];
  6.  
  7. if(Array.isArray(first)) {
  8. // Item is an array, start new call
  9. acc = acc.concat(f(first, []));
  10. } else {
  11. // Add iem to accumulator
  12. acc.push(first);
  13. }
  14.  
  15. // Continue with next item
  16. return f(arr.slice(1), acc);
  17. } else {
  18. // Nothing to do, return accumulator
  19. return acc;
  20. }
  21. };
  22.  
  23. // Start
  24. return f(array, []);
  25. };
  26.  
  27. // console.log('Result:',flatten([1, [2, 3], 4, [5, [6, [7, 8]]], 9, 0]));
  28.  
  29. module.exports = flatten;
Add Comment
Please, Sign In to add comment