groupBy.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import _checkForMethod from "./internal/_checkForMethod.js";
  2. import _curry2 from "./internal/_curry2.js";
  3. import reduceBy from "./reduceBy.js";
  4. /**
  5. * Splits a list into sub-lists stored in an object, based on the result of
  6. * calling a key-returning function on each element, and grouping the
  7. * results according to values returned.
  8. *
  9. * Dispatches to the `groupBy` method of the second argument, if present.
  10. *
  11. * Acts as a transducer if a transformer is given in list position.
  12. *
  13. * @func
  14. * @memberOf R
  15. * @since v0.1.0
  16. * @category List
  17. * @typedefn Idx = String | Int | Symbol
  18. * @sig Idx a => (b -> a) -> [b] -> {a: [b]}
  19. * @param {Function} fn Function :: a -> Idx
  20. * @param {Array} list The array to group
  21. * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
  22. * that produced that key when passed to `fn`.
  23. * @see R.reduceBy, R.transduce, R.indexBy, R.collectBy
  24. * @example
  25. *
  26. * const byGrade = R.groupBy(function(student) {
  27. * const score = student.score;
  28. * return score < 65 ? 'F' :
  29. * score < 70 ? 'D' :
  30. * score < 80 ? 'C' :
  31. * score < 90 ? 'B' : 'A';
  32. * });
  33. * const students = [{name: 'Abby', score: 84},
  34. * {name: 'Eddy', score: 58},
  35. * // ...
  36. * {name: 'Jack', score: 69}];
  37. * byGrade(students);
  38. * // {
  39. * // 'A': [{name: 'Dianne', score: 99}],
  40. * // 'B': [{name: 'Abby', score: 84}]
  41. * // // ...,
  42. * // 'F': [{name: 'Eddy', score: 58}]
  43. * // }
  44. */
  45. var groupBy =
  46. /*#__PURE__*/
  47. _curry2(
  48. /*#__PURE__*/
  49. _checkForMethod('groupBy',
  50. /*#__PURE__*/
  51. reduceBy(function (acc, item) {
  52. acc.push(item);
  53. return acc;
  54. }, [])));
  55. export default groupBy;