Skip to main content
Deno 2 is finally here 🎉️
Learn more
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function groupBy
import { groupBy } from "https://deno.land/std@0.193.0/collections/group_by.ts";

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.

Examples

Example 1

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

const people = [
  { 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

T
K extends string

Parameters

iterable: Iterable<T>
selector: (element: T, index: number) => K

Returns

Partial<Record<K, T[]>>