associateBy
import { associateBy } from "jsr:@ende/collections";function
function associateBy<T>(array: Iterable<T>, selector: (el: T) => string): Record<string, T>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).
array: Iterable<T>The array to transform.
selector: (el: T) => stringThe function to extract the key from each element.
Returns
A record with the keys produced by the selector and the elements as values.
Example: Basic usage
import { associateBy } from "@ende/collections/associate-by";
import { assertEquals } from "@ende/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" },
});