Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. // unwraps one level by accumulating the
  2. // array concatenation of one item with the next item
  3. const unwrap = arr => arr.reduce((acc, item) => acc.concat(item), []);
  4.  
  5. // flattens an array with nested array items
  6. const flatten = arr => {
  7. const needsUnwrapping = arr.filter( i => Array.isArray(i)).length > 0;
  8. if (!needsUnwrapping) {
  9. return arr;
  10. }
  11. return flatten(unwrap(arr));
  12. };
  13.  
  14. // ------
  15.  
  16. //tests
  17. const a = [[1], [2], [3], [4]];
  18. const b = [1, [2], [[3, [4]]]];
  19. const c = [[1, 2, [3]], 4];
  20. const answer = [1, 2, 3, 4];
  21.  
  22. const isCorrect = arr => JSON.stringify(arr) === JSON.stringify(answer);
  23.  
  24. console.log(isCorrect(flatten(a)));
  25. console.log(isCorrect(flatten(b)));
  26. console.log(isCorrect(flatten(c)));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement