Skip to main content
Module

x/aitertools/mod.ts>groupBy

Well-tested utility functions dealing with async iterables
Go to Latest
function groupBy
import { groupBy } from "https://deno.land/x/aitertools@0.5.0/mod.ts";

Groups elmenets of an async interable source according to a specified keySelector function and creates a map of each group key to the elements in that group. Key values are compared using the === operator.

import { groupBy } from "./unique.ts";

interface IdName { id: number; name: string; }
async function* gen(): AsyncIterableIterator<IdName> {
  yield { id: 1, name: "foo" };
  yield { id: 2, name: "bar" };
  yield { id: 3, name: "bar" };
  yield { id: 4, name: "foo" };
}

const map = await groupBy<string, IdName>(gen(), o => o.name);
console.log(map);

The above example will print the following:

Map {
 "foo" => [ { id: 1, name: "foo" }, { id: 4, name: "foo" } ],
 "bar" => [ { id: 2, name: "bar" }, { id: 3, name: "bar" } ]
}

Type Parameters

K

The type of the grouping keys.

E

The type of the elements in the source.

Parameters

source: Iterable<E> | AsyncIterable<E>

An async iterable to group elements from. It has to be finite.

keySelector: (element: E) => K | Promise<K>

A function to to extract the key for each element. It can be either sync or async.

Returns

Promise<Map<K, E[]>>

A map of each group key to the elements in that group.