Function associateBy
- associate
By <T>(array, selector): Record<string, T> Type Parameters
Parameters
Returns Record<string, T>
A record with the keys produced by the selector and the elements as values.
Example: Basic usage
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" },
});
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).