@monstermann/fn
Version:
A utility library for TypeScript.
37 lines (35 loc) • 1.01 kB
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/array/groupBy.ts
/**
* `groupBy(array, grouper, transform?)`
*
* Groups elements in `array` by the result of calling `grouper` function on each element, optionally transforming each element with `transform`, returning an object with keys as group values and values as arrays of elements.
*
* ```ts
* groupBy(
* [1, 2, 3, 4],
* (x) => (x % 2 === 0 ? "even" : "odd"),
* (x) => x * 10,
* ); // { even: [20, 40], odd: [10, 30] }
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* groupBy(
* (x) => (x % 2 === 0 ? "even" : "odd"),
* (x) => x * 10,
* ),
* ); // { even: [20, 40], odd: [10, 30] }
* ```
*/
const groupBy = dfdlT((target, by, transform) => {
return target.reduce((acc, value, idx) => {
const key = by(value, idx, target);
acc[key] ??= [];
acc[key].push(transform ? transform(value, key, idx, target) : value);
return acc;
}, {});
}, (args) => Array.isArray(args[0]));
//#endregion
export { groupBy };