You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

4 years ago
  1. # `flatten()`
  2. The flatten method flattens a multi-dimensional collection into a single dimension:
  3. ```js
  4. const collection = collect({
  5. club: 'Liverpool',
  6. players: ['Salah', 'Firmino', 'Mané'],
  7. });
  8. const flattened = collection.flatten();
  9. flattened.all();
  10. // ['Liverpool', 'Salah', 'Firmino', 'Mané'];
  11. ```
  12. You may optionally pass the function a "depth" argument:
  13. ```js
  14. const collection = collect({
  15. Apple: [
  16. {
  17. name: 'iPhone 6S',
  18. brand: 'Apple',
  19. },
  20. ],
  21. Samsung: [
  22. {
  23. name: 'Galaxy S7',
  24. brand: 'Samsung',
  25. },
  26. ],
  27. });
  28. const flattened = collection.flatten(1);
  29. flattened.all();
  30. // [
  31. // { name: 'iPhone 6S', brand: 'Apple' },
  32. // { name: 'Galaxy S7', brand: 'Samsung' },
  33. // ]
  34. ```
  35. In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in `['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']`. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.
  36. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/flatten.js)