Hyperlinkv0.8.0-beta.28

Array

Array.groupByconsteffect/Array.ts:3058
<A, K extends string | symbol>(f: (a: A) => K): (
  self: Iterable<A>
) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>
<A, K extends string | symbol>(self: Iterable<A>, f: (a: A) => K): Record<
  Record.ReadonlyRecord.NonLiteralKey<K>,
  NonEmptyArray<A>
>

Groups elements into a record by a key-returning function. Each key maps to a NonEmptyArray of elements that produced that key.

When to use

Use to build buckets of elements indexed by a computed string or symbol key.

Details

Unlike group and groupWith, elements do not need to be adjacent to be grouped together. The key function must return a string or symbol.

Example (Grouping by a property)

import { Array } from "effect"

const people = [
  { name: "Alice", group: "A" },
  { name: "Bob", group: "B" },
  { name: "Charlie", group: "A" }
]

const result = Array.groupBy(people, (person) => person.group)
console.log(result)
// { A: [{ name: "Alice", group: "A" }, { name: "Charlie", group: "A" }], B: [{ name: "Bob", group: "B" }] }
Source effect/Array.ts:305823 lines
export const groupBy: {
  <A, K extends string | symbol>(
    f: (a: A) => K
  ): (self: Iterable<A>) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>
  <A, K extends string | symbol>(
    self: Iterable<A>,
    f: (a: A) => K
  ): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>
} = dual(2, <A, K extends string | symbol>(
  self: Iterable<A>,
  f: (a: A) => K
): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>> => {
  const out: Record<string | symbol, NonEmptyArray<A>> = {}
  for (const a of self) {
    const k = f(a)
    if (Object.hasOwn(out, k)) {
      out[k].push(a)
    } else {
      out[k] = [a]
    }
  }
  return out
})
Referenced by 1 symbols