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.

31 lines
745 B

4 years ago
  1. 'use strict';
  2. var nestedValue = require('../helpers/nestedValue');
  3. var _require = require('../helpers/is'),
  4. isFunction = _require.isFunction;
  5. module.exports = function groupBy(key) {
  6. var _this = this;
  7. var collection = {};
  8. this.items.forEach(function (item, index) {
  9. var resolvedKey = void 0;
  10. if (isFunction(key)) {
  11. resolvedKey = key(item, index);
  12. } else if (nestedValue(item, key) || nestedValue(item, key) === 0) {
  13. resolvedKey = nestedValue(item, key);
  14. } else {
  15. resolvedKey = '';
  16. }
  17. if (collection[resolvedKey] === undefined) {
  18. collection[resolvedKey] = new _this.constructor([]);
  19. }
  20. collection[resolvedKey].push(item);
  21. });
  22. return new this.constructor(collection);
  23. };