flattenDepth.js 787 B

123456789101112131415161718192021222324252627282930313233
  1. var baseFlatten = require('./_baseFlatten'),
  2. toInteger = require('./toInteger');
  3. /**
  4. * Recursively flatten `array` up to `depth` times.
  5. *
  6. * @static
  7. * @memberOf _
  8. * @since 4.4.0
  9. * @category Array
  10. * @param {Array} array The array to flatten.
  11. * @param {number} [depth=1] The maximum recursion depth.
  12. * @returns {Array} Returns the new flattened array.
  13. * @example
  14. *
  15. * var array = [1, [2, [3, [4]], 5]];
  16. *
  17. * _.flattenDepth(array, 1);
  18. * // => [1, 2, [3, [4]], 5]
  19. *
  20. * _.flattenDepth(array, 2);
  21. * // => [1, 2, 3, [4], 5]
  22. */
  23. function flattenDepth(array, depth) {
  24. var length = array == null ? 0 : array.length;
  25. if (!length) {
  26. return [];
  27. }
  28. depth = depth === undefined ? 1 : toInteger(depth);
  29. return baseFlatten(array, depth);
  30. }
  31. module.exports = flattenDepth;