reduceGroups

import { reduceGroups } from "jsr:@ende/collections";

function

function reduceGroups<T, A>(record: Readonly<Record<string, ReadonlyArray<T>>>, reducer: (accumulator: A, current: T) => A, initialValue: A): Record<string, A>

Applies the given reducer to each group in the given grouping, returning the results together with the respective group keys.

record: Readonly<Record<string, ReadonlyArray<T>>>

The grouping to reduce.

reducer: (accumulator: A, current: T) => A

The reducer function to apply to each group.

initialValue: A

The initial value of the accumulator.

Returns

A record with the same keys as the input grouping, where each value is the result of applying the reducer to the respective group.

Example: Basic usage

import { reduceGroups } from "@ende/collections/reduce-groups";
import { assertEquals } from "@ende/assert";

const votes = {
  Woody: [2, 3, 1, 4],
  Buzz: [5, 9],
};

const totalVotes = reduceGroups(votes, (sum, vote) => sum + vote, 0);

assertEquals(totalVotes, {
  Woody: 10,
  Buzz: 14,
});

Source