Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. var arr1 = [1, 2, [3, 4]];
  2.  
  3. var arr2 = flattenDeep(arr1, 1);
  4.  
  5. function flattenDeep(arr, depthValue) {
  6. if (Array.prototype.flat) {
  7. console.log('11');
  8. return arr.flat(depthValue);
  9. } else {
  10. console.log('22');
  11. var depth = depthValue;
  12. depth = depth === undefined ? 1 : Math.floor(depth);
  13. if (depth < 1) return Array.prototype.slice.call(this);
  14. return (function flat(arr, depth) {
  15. var len = arr.length >>> 0;
  16. var flattened = [];
  17. var i = 0;
  18. while (i < len) {
  19. if (i in arr) {
  20. var el = arr[i];
  21. if (Array.isArray(el) && depth > 0)
  22. flattened = flattened.concat(flat(el, depth - 1));
  23. else flattened.push(el);
  24. }
  25. i++;
  26. }
  27. return flattened;
  28. })(this, depth);
  29. }
  30. }
  31.  
  32.  
  33. console.log(arr2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement