Function reduceGroups

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

    Type Parameters

    • T

      input type of an item in a group in the given grouping.

    • A

      type of the accumulator value, which will match the returned record's values.

    Parameters

    • record: Readonly<Record<string, readonly T[]>>

      The grouping to reduce.

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

      The reducer function to apply to each group.

        • (accumulator, current): A
        • Parameters

          • accumulator: A
          • current: T

          Returns A

    • initialValue: A

      The initial value of the accumulator.

    Returns Record<string, A>

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

    import { reduceGroups } from "@std/collections/reduce-groups";
    import { assertEquals } from "@std/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,
    });