Skip to main content
The Deno 2 Release Candidate is here
Learn more
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function associateBy
import { associateBy } from "https://deno.land/std@0.139.0/collections/mod.ts";

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).

Example:

import { associateBy } from "https://deno.land/std@0.139.0/collections/mod.ts"
import { assertEquals } from "https://deno.land/std@0.139.0/testing/asserts.ts";

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' },
})

Parameters

array: readonly T[]
selector: (el: T) => string

Returns

Record<string, T>