Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. /*
  2. Let's set up some example arrays with arbitrarily
  3. nested arrays within
  4. */
  5. const array1 = ['a', 'b', ['c', 'd']]
  6. const array2 = ['a', ['b', 'c'], 'd']
  7. const array3 = ['a', ['b', ['c', 'd']], 'e']
  8.  
  9. /*
  10. We'll use the prototype reduce() function.
  11. It takes a callback and an initial value.
  12. It will establish an accumulator with the initial value.
  13. It will then execute the callback on each item in the array.
  14.  
  15. We will make a function that will take an array,
  16. use the reduce() method to run a callback that appends
  17. each value to the accumulator. If the value is another
  18. array, it will call itself recursively against that array.
  19. This will allow it to flatten an infinite number of nested
  20. arrays into a single flat array
  21. */
  22. const flatten = (array) => array.reduce(
  23. (acc, val) => acc.concat(
  24. Array.isArray(val) ? flatten(val) : val
  25. ), []
  26. )
  27.  
  28. /*
  29. Let's test it out on our arrays
  30. */
  31. const flatArray1 = flatten(array1);
  32. const flatArray2 = flatten(array2);
  33. const flatArray3 = flatten(array3);
  34.  
  35. /*
  36. And log our results to the console
  37. */
  38. console.log(flatArray1); // logs '["a", "b", "c", "d"]'
  39. console.log(flatArray2); // logs '["a", "b", "c", "d"]'
  40. console.log(flatArray3); // logs '["a", "b", "c", "d", "e"]'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement