flatten.js 629 B

123456789101112131415161718192021222324252627282930
  1. var isArray = require('../type/is-array');
  2. var each = require('../each');
  3. /**
  4. * Flattens `array` a single level deep.
  5. *
  6. * @param {Array} arr The array to flatten.
  7. * @return {Array} Returns the new flattened array.
  8. * @example
  9. *
  10. * flatten([1, [2, [3, [4]], 5]]); // => [1, 2, [3, [4]], 5]
  11. */
  12. var flatten = function flatten(arr) {
  13. if (!isArray(arr)) {
  14. return arr;
  15. }
  16. var result = [];
  17. each(arr, function (item) {
  18. if (isArray(item)) {
  19. each(item, function (subItem) {
  20. result.push(subItem);
  21. });
  22. } else {
  23. result.push(item);
  24. }
  25. });
  26. return result;
  27. };
  28. module.exports = flatten;