groupBy.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var isEmpty = require('./isEmpty')
  2. var isObject = require('./isObject')
  3. var isFunction = require('./isFunction')
  4. var property = require('./property')
  5. var each = require('./each')
  6. function createiterateEmpty (iterate) {
  7. return function () {
  8. return isEmpty(iterate)
  9. }
  10. }
  11. /**
  12. * 集合分组,默认使用键值分组,如果有iterate则使用结果进行分组
  13. *
  14. * @param {Array} obj 对象
  15. * @param {Function} iterate 回调/对象属性
  16. * @param {Object} context 上下文
  17. * @return {Object}
  18. */
  19. function groupBy (obj, iterate, context) {
  20. var groupKey
  21. var result = {}
  22. if (obj) {
  23. if (iterate && isObject(iterate)) {
  24. iterate = createiterateEmpty(iterate)
  25. } else if (!isFunction(iterate)) {
  26. iterate = property(iterate)
  27. }
  28. each(obj, function (val, key) {
  29. groupKey = iterate ? iterate.call(context, val, key, obj) : val
  30. if (result[groupKey]) {
  31. result[groupKey].push(val)
  32. } else {
  33. result[groupKey] = [val]
  34. }
  35. })
  36. }
  37. return result
  38. }
  39. module.exports = groupBy