groupBy

Buckets every element into a Map<K, List<A>> by a computed key.

Map<K, List<A>> groupBy<A, K>(K Function(A a) f, Iterable<A> iterable) Future<Map<K, List<A>>> groupByAsync<A, K>(FutureOr<K> Function(A a) f, FxAsyncIterable<A> iterable) Map<K, List<T>> Fx.groupBy<K>(K Function(T a) f) // chain (sync) Future<Map<K, List<T>>> FxAsync.groupBy<K>(FutureOr<K> Function(T a) f) // chain (async)

Lecture

groupBy is a terminal operator that pulls the whole pipeline and sorts each value into a bucket, keyed by whatever f returns for it. Every element is kept — nothing is dropped, unlike filter — it's just reorganized into buckets.

FxTS's version returns a plain JS object; since Dart has no anonymous object literal with arbitrary computed keys, FxDart returns a Map<K, List<A>> instead — one of the standard TS-object-to-Dart-Map conversions used throughout this section (indexBy and countBy do the same).

Order matters within each bucket: elements land in each list in the same relative order they appeared in the source. And because it's a terminal, this works exactly the same whether the upstream pipeline is a plain list or a chain of lazy map/filter steps — you just pay the cost once, when groupBy pulls it.

Demo 1 · Basics

Demo 2 · Async

Try it yourself

Exercise: group the words by their length.

Related: indexBy — one value per key instead of a list · countBy — count per key instead of collecting · partition — grouping into exactly two buckets