Files
lodash/groupBy.js
2017-01-09 17:38:33 -08:00

37 lines
1.2 KiB
JavaScript

import baseAssignValue from './_baseAssignValue.js';
import createAggregator from './_createAggregator.js';
/** Used for built-in method references. */
const objectProto = Object.prototype;
/** Used to check objects for own properties. */
const hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*/
const groupBy = createAggregator((result, value, key) => {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
export default groupBy;