js-fns
Version:
Modern JavaScript utility library focused on the build size
34 lines (31 loc) • 1.04 kB
JavaScript
/**
* Creates an object where the key is the group id and the value is an array of elements grouped by this id.
*
* @param array - The array to group elements from
* @param mapper - The function that returns the group id
* @returns An object where the key is the group id and the value is an array of elements grouped by this id
*
* @public
*/
/**
* Creates an object where the key is the group id and the value is an array of elements grouped by this id.
*
* @param array - The array to group elements from
* @param key - The name of the field to use as the id
* @returns An object where the key is the group id and the value is an array of elements grouped by this id
*
* @public
*/
/**
* @category Array
* @internal
*/
export default function group(array, mapper) {
return array.reduce(function (acc, element, index) {
var groupId =
typeof mapper === 'function' ? mapper(element, index) : element[mapper]
acc[groupId] = acc[groupId] || []
acc[groupId].push(element)
return acc
}, {})
}