std/collections/mod.ts

Deno standard library
Go to Latest
function groupBy
import { groupBy } from "https://deno.land/std@0.139.0/collections/mod.ts?s=groupBy";

Applies the given selector to each element in the given array, returning a Record containing the results as keys and all values that produced that key as values.

Example:

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

type Person = {
  name: string;
};

const people: Person[] = [
    { name: 'Anna' },
    { name: 'Arnold' },
    { name: 'Kim' },
];
const peopleByFirstLetter = groupBy(people, it => it.name.charAt(0))

assertEquals(peopleByFirstLetter, {
    'A': [ { name: 'Anna' }, { name: 'Arnold' } ],
    'K': [ { name: 'Kim' } ],
})

Type Parameters

K extends string[src]

Parameters

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

Returns

Partial<Record<K, T[]>>[src]