Home Reference Source

ts_temp/array/flatten.js

  1. import isArrayLike from '../is/arrayLike';
  2. /**
  3. * Returns a new list by pulling every item out of it (and all its sub-arrays)
  4. * and putting them in a new array, depth-first.
  5. *
  6. * @param {Array} arr The array to consider.
  7. * @return {Array} The flattened list.
  8. * @example
  9. *
  10. * flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
  11. * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  12. */
  13. const flatten = (arr = []) => {
  14. const result = [];
  15. for (let i = 0; i < arr.length; i++) {
  16. const a = arr[i];
  17. if (isArrayLike(a)) {
  18. const nested = flatten(a);
  19. for (let j = 0; j < nested.length; j++) {
  20. result.push(nested[j]);
  21. }
  22. }
  23. else {
  24. result.push(a);
  25. }
  26. }
  27. return result;
  28. };
  29. export default flatten;