Function groupArrayBy

  • Group an array using a grouping function into an object

    Returns

    an object containing arrays with an entry for each group

    Example

    const { odd, even } = groupArrayBy([1, 2, 3, 4], x => x % 2 === 0 ? 'even' : 'odd')
    // odd === [1, 3]
    // even === [2, 4]

    Example

    const peopleByAge = groupArrayBy([
    { name: 'John', age: 20 },
    { name: 'Claire', age: 20 },
    { name: 'Ben', age: 23 }
    ], person => person.age)
    peopleByAge === {
    20: [
    { name: 'John', age: 20 },
    { name: 'Claire', age: 20 }
    ],
    23: [
    { name: 'Ben', age: 23 }
    ]
    }

    Type Parameters

    • T

    • K extends PropertyKey

    Parameters

    • array: T[]

      the array to create groups from

    • groupFn: ((element) => K)

      the keys to group by. Elements which return the same key when passed to this function will be in the same group

        • (element): K
        • Parameters

          • element: T

          Returns K

    Returns Record<K, T[]>

Generated using TypeDoc