Skip to content

Array.groupBy ​

ant
func Array.groupBy[T, K](xs: Array[T], key: func(T): K): Map[K, Array[T]]

Array.groupBy returns a map from each key to the elements of xs with that key. Keys are in first-seen order and each group keeps the order of xs.

Details ​

  • Keys are in the order they first appear, and each group keeps the order of xs. An empty xs gives an empty map.
  • Calls key once per element, from first to last.
  • Keys compare by ==, so a record or an array can be a key.
  • Returns a new map of new arrays; xs is unchanged.

Basic examples ​

Group numbers by their remainder. The key 1 comes first because 1 is the first element:

ant
Array.groupBy([1, 2, 3, 4, 5], { x % 2 }) // Map{ 1: [1, 3, 5], 0: [2, 4] }

Call it through . on the array to group words by their first letter:

ant
let fruit = ["apple", "avocado", "banana", "blueberry", "cherry"]
fruit.groupBy({ x.slice(0, 1) }) // Map{ "a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"] }

Scope ​

An empty array gives an empty map. Annotate it so that T is known:

ant
let empty: Array[int] = []
empty.groupBy({ x }) // Map{}

A named function works as well as a lambda, and so does a function of the prelude:

ant
func parity(n: int): string {
  if n % 2 == 0 { "even" } else { "odd" }
}

Array.range(1, 7).groupBy(parity)                                    // Map{ "odd": [1, 3, 5], "even": [2, 4, 6] }
["ant", "bee", "wasp", "moth", "fly"] | Array.groupBy(String.length) // Map{ 3: ["ant", "bee", "fly"], 4: ["wasp", "moth"] }

Name the arguments when that reads better:

ant
Array.groupBy(xs: [3, 1, 2], key: { x > 1 }) // Map{ true: [3, 2], false: [1] }

Group records by a field:

ant
type Person = { name: string, team: string }
let people = [
  Person{ name: "Ann", team: "red" },
  Person{ name: "Bob", team: "blue" },
  Person{ name: "Cid", team: "red" },
]
people.groupBy({ x.team })["red"] // [Person{ name: "Ann", team: "red" }, Person{ name: "Cid", team: "red" }]

A record or an array can be the key, since keys compare by ==:

ant
type Cell = { row: int, col: int }
[1, 2, 3, 4].groupBy({ Cell{ row: x % 2, col: 0 } }) // Map{ Cell{ row: 1, col: 0 }: [1, 3], Cell{ row: 0, col: 0 }: [2, 4] }
[1, 2, 3, 4].groupBy({ [x % 2] })                    // Map{ [1]: [1, 3], [0]: [2, 4] }

null is a key like any other, and a nullable element can be grouped on whether it is null:

ant
let xs: Array[int | null] = [1, null, 2, null]
xs.groupBy({ x })         // Map{ 1: [1], null: [null, null], 2: [2] }
xs.groupBy({ x == null }) // Map{ false: [1, 2], true: [null, null] }

Use is in the key to group the members of a union by type:

ant
type Circle = { r: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ r: 1.0 }, Square{ side: 2.0 }, Circle{ r: 3.0 }]
shapes.groupBy({ if x is Circle { "circle" } else { "square" } }) // Map{ "circle": [Circle{ r: 1.0 }, Circle{ r: 3.0 }], "square": [Square{ side: 2.0 }] }

Group the characters of a string by splitting it into graphemes first:

ant
"🐜a🐜b".graphemes().groupBy({ x }) // Map{ "🐜": ["🐜", "🐜"], "a": ["a"], "b": ["b"] }

Applications ​

Count how often each word occurs:

ant
let words = ["the", "ant", "and", "the", "bee"]
words.groupBy({ x }).map({ len(x.value) }) // Map{ "the": 2, "ant": 1, "and": 1, "bee": 1 }

Print a roster by team:

ant
type Person = { name: string, team: string }
let people = [
  Person{ name: "Ann", team: "red" },
  Person{ name: "Bob", team: "blue" },
  Person{ name: "Cid", team: "red" },
]
for entry in people.groupBy({ x.team }).entries() {
  let names = entry.value.map({ x.name })
  println("${entry.key}: ${String.join(names, ", ")}")
}
text
red: Ann, Cid
blue: Bob

Total the amounts of each category:

ant
type Expense = { category: string, amount: int }
let expenses = [
  Expense{ category: "food", amount: 12 },
  Expense{ category: "rent", amount: 900 },
  Expense{ category: "food", amount: 30 },
]
expenses.groupBy({ x.category }).map({ x.value.map({ x.amount }).sum() ?? 0 }) // Map{ "food": 42, "rent": 900 }

Properties and relations ​

Flattening the groups gives every element once. The order changes when keys interleave:

ant
let xs = [5, 3, 8, 1]
let groups = xs.groupBy({ x > 4 })
assert(groups.values().flatten() == [5, 8, 3, 1])
assert(len(groups.values().flatten()) == len(xs))

The keys are the distinct keys of the elements, in first-seen order, and every element sits under its own key:

ant
let xs = [5, 3, 8, 1]
let key = func(n: int): bool { n > 4 }
let groups = xs.groupBy(key)
assert(groups.keys() == xs.map(key).unique())
for entry in groups.entries() {
  assert(entry.value.every({ key(x) == entry.key }))
}

Each group is what Array.filter keeps for its key:

ant
let xs = [1, 2, 3, 4, 5, 6]
let groups = xs.groupBy({ x % 3 })
for entry in groups.entries() {
  assert(entry.value == xs.filter({ x % 3 == entry.key }))
}

key runs once per element, in the order of xs, so a side effect in it sees every element:

ant
let seen: Array[int] = []
[3, 1, 4, 1].groupBy({ seen.push(x); x % 2 }) // Map{ 1: [3, 1, 1], 0: [4] }
seen                                          // [3, 1, 4, 1]

The groups are new arrays, so changing one leaves xs as it was:

ant
let xs = [5, 3, 8, 1]
let big: Array[int] = xs.groupBy({ x > 4 })[true] ?? []
big.push(100)
assert(xs == [5, 3, 8, 1])

Possible issues ​

Indexing the result reads Array[T] | null, because a key may have no group. Calling a function on it without narrowing is a compile error:

ant
let groups = [1, 2, 3].groupBy({ x % 2 })
println(groups[1].length())
// error: Array[int] | null has no field or function length on every member: narrow the value first

Supply an empty group with ??; the [] takes the element type of the group:

ant
let groups = [1, 2, 3].groupBy({ x % 2 })
let odd = groups[1] ?? []
let sevens = groups[7] ?? []
odd    // [1, 3]
sevens // []

The keys are in first-seen order, not sorted. Sort them when the order matters:

ant
let groups = [1, 2, 3, 4, 5].groupBy({ x % 2 })
groups.keys()        // [1, 0]
groups.keys().sort() // [0, 1]

NaN is not == to itself, so every NaN key starts a group of its own:

ant
[1.0, Math.NaN, Math.NaN].groupBy({ x }) // Map{ 1.0: [1.0], NaN: [NaN], NaN: [NaN] }

A key is hashed when the map gets it. When key returns an element itself, such as an array, mutating that element afterwards mutates the key, and the group may become unreachable. Return a copy, as in { [...x] }, or do not mutate the elements:

ant
let rows = [[1], [2], [1]]
let groups = rows.groupBy({ [...x] })
rows[0].push(9)
groups[[1]] // [[1, 9], [1]]

The copy protects the key only. The group holds the elements themselves, so it shows the push.

See also ​

Array.uniqueBy · Array.filter · Array.countWhere · Array.chunk · Array.sortBy · Map.map · Map.keys · Map.values