array-group-by.js 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. var bind = require('../internals/function-bind-context');
  2. var IndexedObject = require('../internals/indexed-object');
  3. var toObject = require('../internals/to-object');
  4. var toLength = require('../internals/to-length');
  5. var toPropertyKey = require('../internals/to-property-key');
  6. var objectCreate = require('../internals/object-create');
  7. var arrayFromConstructorAndList = require('../internals/array-from-constructor-and-list');
  8. var push = [].push;
  9. module.exports = function ($this, callbackfn, that, specificConstructor) {
  10. var O = toObject($this);
  11. var self = IndexedObject(O);
  12. var boundFunction = bind(callbackfn, that, 3);
  13. var target = objectCreate(null);
  14. var length = toLength(self.length);
  15. var index = 0;
  16. var Constructor, key, value;
  17. for (;length > index; index++) {
  18. value = self[index];
  19. key = toPropertyKey(boundFunction(value, index, O));
  20. // in some IE10 builds, `hasOwnProperty` returns incorrect result on integer keys
  21. // but since it's a `null` prototype object, we can safely use `in`
  22. if (key in target) push.call(target[key], value);
  23. else target[key] = [value];
  24. }
  25. if (specificConstructor) {
  26. Constructor = specificConstructor(O);
  27. if (Constructor !== Array) {
  28. for (key in target) target[key] = arrayFromConstructorAndList(Constructor, target[key]);
  29. }
  30. } return target;
  31. };