Guest User

Untitled

a guest
Apr 26th, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. 'use strict';
  2.  
  3. // see if the array is already flattened
  4. // returns true or false
  5. const isArrayFlattened = function($array) {
  6. if (!$array) {
  7. return true;
  8. }
  9. for (const item of $array) {
  10. if (item instanceof Array) {
  11. return false;
  12. }
  13. }
  14. return true;
  15. };
  16.  
  17. // main function to flatten the arrays. The use of Array.prototype.reduce is so that each iteration
  18. // a (potential) layer of square brackets is removed.
  19. // This is ensured by that [1].concat(2).concat(3) returns the same value as
  20. // [1].concat([2, 3]), which is [1, 2, 3] for both
  21. const flatten = function($array) {
  22. while (!isArrayFlattened($array)) {
  23. $array = $array.reduce((previous, item) => {
  24. return previous.concat(item);
  25. }, []);
  26. }
  27. return $array;
  28. };
  29.  
  30. console.log(flatten([])); // []
  31. console.log(flatten([1, [2], 3])); // [1, 2, 3]
  32. console.log(flatten([[1, 2], 3])); // [1, 2, 3]
  33. console.log(flatten([[[1], 2], 3])); // [1, 2, 3]
  34. console.log(flatten([[[[1]], 2], 3])); // [1, 2, 3]
  35. console.log(flatten([[1], [2], [3]])); // [1, 2, 3]
  36. console.log(flatten([[[[1], [2]], [3]]])); // [1, 2, 3]
Add Comment
Please, Sign In to add comment