Star
Docs/v5/get-started/filter-partition-groupby

filter, partition & groupBy

The filter(), partition() and groupBy() methods are similar in that they all divide a collection into parts based on applying a function to each element. All three call the predicate or grouping function once for each item in the input collection. All three return zero or more collections of the same type as their input. The returned collections are always distinct from the input (according to ===), even if the contents are identical.

filter()

Of these methods, filter() is the only one that is lazy and the only one which discards items from the input collection. It is the simplest to use, and the fact that it returns exactly one collection makes it easy to combine with other methods to form a pipeline of operations.

partition()

The partition() method is similar to an eager version of filter(), but it returns two collections: the first contains the items that would have been discarded by filter(), and the second contains the items that would have been kept. It always returns an array of exactly two collections, which can make it easier to use than groupBy(). Compared to making two separate calls to filter(), partition() makes half as many calls to the predicate passed to it.

groupBy()

The groupBy() method is a more generalized version of partition() that can group by an arbitrary function rather than just a predicate. It returns a map with zero or more entries, where the keys are the values returned by the grouping function, and the values are nonempty collections of the corresponding arguments.

Although groupBy() is more powerful than partition(), it can be harder to use because it is not always possible to predict in advance how many entries the returned map will have and what their keys will be.

Side by side

SummaryfilterpartitiongroupBy
ease of useeasiestmoderatehardest
generalityleastmoderatemost
lazinesslazyeagereager
# of returned sub-collections120 or more
sub-collections may be emptyyesyesno
can discard itemsyesnono
wrapping containernonearrayMap/OrderedMap