Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. // Takes an array of arbitrary depth
  2. // Returns a flattened array of all @array's elements
  3. const arrayFlatten = (array) => {
  4. let flattened = [...array];
  5. while (flattened.some(el => Array.isArray(el))) {
  6. flattened = flattened.reduce((arr, el) => arr.concat(el), []);
  7. }
  8. return flattened;
  9. }
  10.  
  11. // Example mocha tests
  12. describe('arrayFlatten()', () => {
  13. it('returns unmodified array if already flat', () => {
  14. const array = [1,2,3,4,5,6];
  15. expect(arrayFlatten(array)).to.deep.equal(array);
  16. });
  17.  
  18. it('flattens a 2D array of numbers', () => {
  19. const array2D = [[1,2],[3,4],[5,6]];
  20. const flattened = [1,2,3,4,5,6];
  21. expect(arrayFlatten(array2D)).to.deep.equal(flattened);
  22. });
  23.  
  24. it('flattens an array of arbitrary depth', () => {
  25. const deepArray = [[[[1,2,[3,4,[5,6],7],8],9,[10,11],12,13],[14,15]],16,17];
  26. const flattened = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
  27. expect(arrayFlatten(deepArray)).to.deep.equal(flattened);
  28. });
  29.  
  30. it('does not directly mutate the passed-in array', () => {
  31. const array = [[1,2],[3,4],[5,6]];
  32. const array2 = [[1,2],[3,4],[5,6]];
  33. arrayFlatten(array);
  34.  
  35. expect(array).to.deep.equal(array2);
  36. })
  37. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement