• Groups an array of objects by a single key and returns an array of GroupedObjects.

    Example

    const arr = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
    { id: 3, name: 'Charlie', age: 30 }
    ];

    groupedByOne(arr, 'age', ['name']);
    // => { ok: true, value:
    // [
    // { group: '30', items: [{ name: 'Alice' }, { name: 'Charlie' }] },
    // { group: '25', items: [{ name: 'Bob' }] }
    // ]

    Example

    Handle an invalid input:

    const emptyArr = [];
    groupedByOne(emptyArr, 'age');
    // => { ok: false, error: Error('[collections.groupedByOne] Input must be an array and cannot be empty') }

    Type Parameters

    • T extends Record<PropertyKey, any>

      The type of objects in the input array.

    Parameters

    • arr: T[]

      The input array to group.

    • key: string

      The key to group the objects by. Can be a dot-separated string to group by nested properties.

    • Optional propertiesToInclude: (keyof T)[]

    Returns Result<GroupedObject<T>[], Error>

    An array of GroupedObjects, each containing a group name and an array of grouped items.

Generated using TypeDoc v0.24.7