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

x/ayonli_jsext/array/index.ts>groupBy

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

Groups the items of the array according to the comparable values returned by a provided callback function.

The returned record / map has separate properties for each group, containing arrays with the items in the group.

Examples

Example 1

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

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

console.log(groupBy(arr, item => item.name));
// {
//     foo: [
//         { id: 1, name: "foo" },
//         { id: 3, name: "foo" }
//     ],
//     bar: [
//         { id: 2, name: "bar" },
//         { id: 5, name: "bar" }
//     ],
//     baz: [
//         { id: 4, 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 { groupBy } from "@ayonli/jsext/array";

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

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

Parameters

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

Returns

Map<K, T[]>