Function associateBy

  • Creates a record by associating each element of the input array with a key generated by the selector function.

    If the selector produces the same key for multiple elements, the latest one will be used (overriding the ones before it).

    Type Parameters

    • T

      Type of the elements in the input array.

    Parameters

    • array: Iterable<T, any, any>

      The array to transform.

    • selector: ((el: T) => string)

      The function to extract the key from each element.

        • (el): string
        • Parameters

          • el: T

          Returns string

    Returns Record<string, T>

    A record with the keys produced by the selector and the elements as values.

    import { associateBy } from "@std/collections/associate-by";
    import { assertEquals } from "@std/assert";

    const users = [
    { id: "a2e", userName: "Anna" },
    { id: "5f8", userName: "Arnold" },
    { id: "d2c", userName: "Kim" },
    ];

    const usersById = associateBy(users, (user) => user.id);

    assertEquals(usersById, {
    "a2e": { id: "a2e", userName: "Anna" },
    "5f8": { id: "5f8", userName: "Arnold" },
    "d2c": { id: "d2c", userName: "Kim" },
    });