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.

108 lines
2.1 KiB

4 years ago
  1. # `groupBy()`
  2. The groupBy method groups the collection's items into multiple collections by a given key:
  3. > If you want to group the collection by keys as a plain object, see [mapToGroups](mapToGroups)
  4. ```js
  5. const collection = collect([
  6. {
  7. product: 'Chair',
  8. manufacturer: 'IKEA',
  9. },
  10. {
  11. product: 'Desk',
  12. manufacturer: 'IKEA',
  13. },
  14. {
  15. product: 'Chair',
  16. manufacturer: 'Herman Miller',
  17. },
  18. ]);
  19. const grouped = collection.groupBy('manufacturer');
  20. grouped.all();
  21. // {
  22. // IKEA: Collection {
  23. // items: [
  24. // {
  25. // id: 100,
  26. // product: 'Chair',
  27. // manufacturer: 'IKEA',
  28. // price: '1490 NOK',
  29. // },
  30. // {
  31. // id: 150,
  32. // product: 'Desk',
  33. // manufacturer: 'IKEA',
  34. // price: '900 NOK',
  35. // },
  36. // ],
  37. // },
  38. // 'Herman Miller': Collection {
  39. // items: [
  40. // {
  41. // id: 200,
  42. // product: 'Chair',
  43. // manufacturer: 'Herman Miller',
  44. // price: '9990 NOK',
  45. // },
  46. // ],
  47. // },
  48. // }
  49. ```
  50. In addition to passing a string key, you may also pass a callback. The callback should return the value you wish to key the group by:
  51. ```js
  52. const collection = collect([
  53. {
  54. product: 'Chair',
  55. manufacturer: 'IKEA',
  56. },
  57. {
  58. product: 'Desk',
  59. manufacturer: 'IKEA',
  60. },
  61. {
  62. product: 'Chair',
  63. manufacturer: 'Herman Miller',
  64. },
  65. ]);
  66. const grouped = collection.groupBy((item, key) => item.manufacturer.substring(0, 3));
  67. grouped.all();
  68. // {
  69. // IKE: Collection {
  70. // items: [
  71. // {
  72. // id: 100,
  73. // product: 'Chair',
  74. // manufacturer: 'IKEA',
  75. // price: '1490 NOK',
  76. // },
  77. // {
  78. // id: 150,
  79. // product: 'Desk',
  80. // manufacturer: 'IKEA',
  81. // price: '900 NOK',
  82. // },
  83. // ],
  84. // },
  85. // Her: Collection {
  86. // items: [
  87. // {
  88. // id: 200,
  89. // product: 'Chair',
  90. // manufacturer: 'Herman Miller',
  91. // price: '9990 NOK',
  92. // },
  93. // ],
  94. // },
  95. // }
  96. ```
  97. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/groupBy.js)