Skip to main content

latest
Works with
It is unknown whether this package works with Node.js, Deno, Browsers, Cloudflare Workers, Bun
It is unknown whether this package works with Node.js
It is unknown whether this package works with Deno
It is unknown whether this package works with Browsers
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Bun
JSR Score70%
Downloads1/wk
Published2 years ago (0.215.0)
function associateBy
associateBy<T>(
array: Iterable<T>,
selector: (el: T) => string
): Record<string, T>

Transforms the given array into a Record, extracting the key of each element using the given selector. If the selector produces the same key for multiple elements, the latest one will be used (overriding the ones before it).

Examples

Example 1

import { associateBy } from "@std/collections/associate_by";
import { assertEquals } from "@std/assert/assert_equals";

const users = [
  { id: "a2e", userName: "Anna" },
  { id: "5f8", userName: "Arnold" },
  { id: "d2c", userName: "Kim" },
];
const usersById = associateBy(users, (it) => it.id);

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

Type Parameters

Parameters

array: Iterable<T>
selector: (el: T) => string

Return Type

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@std/collections

Import symbol

import { associateBy } from "@std/collections";
or

Import directly with a jsr specifier

import { associateBy } from "jsr:@std/collections";