Enum.group_by doesn´t keep sort order

The expected result you showed is different even if you do sort the results. In the input you have one element %{position: 1} and in your expected results there are two elements.

Enum.group_by keeps the input order on the lists it creates for each group. The map keys are not sorted because maps are not an ordered data structure. The order is an implementation detail of the runtime.

EDIT: If you need sort the lists, you can either sort the input list because Enum.group_by keeps that order. Or you can sort each individual list in the result by doing this: Enum.into(result, %{}, fn {key, list} -> {key, Enum.sort(list)} end).

2 Likes