Skip to main content
Home

Built and signed on GitHub Actions

Well-tested utility functions dealing with async iterables

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
88%
Published
2 years ago (0.6.0)
function groupBy
groupBy<
K,
E,
>
(
source: Iterable<E> | AsyncIterable<E>,
keySelector: (element: E) => K | Promise<K>,
): Promise<Map<K, E[]>>

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

The type of the grouping keys.

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.

Return Type

Promise<Map<K, E[]>>

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

New Ticket: 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:@hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";
or

Import directly with a jsr specifier

import { groupBy } from "jsr:@hongminhee/aitertools";

Add Package

pnpm i jsr:@hongminhee/aitertools
or (using pnpm 10.8 or older)
pnpm dlx jsr add @hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";

Add Package

yarn add jsr:@hongminhee/aitertools
or (using Yarn 4.8 or older)
yarn dlx jsr add @hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";

Add Package

vlt install jsr:@hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";

Add Package

npx jsr add @hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";

Add Package

bunx jsr add @hongminhee/aitertools

Import symbol

import { groupBy } from "@hongminhee/aitertools";