Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/array/index.ts>keyBy

A JavaScript extension package for building strong and modern applications.
Latest
function keyBy
import { keyBy } from "https://deno.land/x/ayonli_jsext@v0.9.72/array/index.ts";

Creates a record or map from the items of the array according to the comparable values returned by a provided callback function.

This function is similar to groupBy, except it overrides values if the same property already exists instead of grouping them as a list.

Examples

Example 1

import { keyBy } from "@ayonli/jsext/array";

const arr = [
    { id: 1, name: "foo" },
    { id: 2, name: "bar" },
    { id: 3, name: "baz" },
];

console.log(keyBy(arr, item => item.name));
// {
//     foo: { id: 1, name: "foo" },
//     bar: { id: 2, name: "bar" },
//     baz: { id: 3, name: "baz" }
// }

Type Parameters

T
K extends string | number | symbol

Parameters

arr: T[]
fn: (item: T, i: number) => K
optional
type: ObjectConstructor

Returns

Record<K, T>

Examples

Example 1

import { keyBy } from "@ayonli/jsext/array";

const arr = [
    { id: 1, name: "foo" },
    { id: 2, name: "bar" },
    { id: 3, name: "baz" },
];

console.log(keyBy(arr, item => item.name, Map));
// Map {
//     "foo" => { id: 1, name: "foo" },
//     "bar" => { id: 2, name: "bar" },
//     "baz" => { id: 3, name: "baz" }
// }

Parameters

arr: T[]
fn: (item: T, i: number) => K
type: MapConstructor

Returns

Map<K, T>