Skip to content

tuple group_by into map #21

@ndrean

Description

@ndrean

Suppose you have data in the form [{"M1", "C1"}, {"M1", "C2"}, {"M2", "C3"}] and you want a map "grouped by":
[%{c: ["C2", "C1"], m: "M1"}, %{c: ["C3"], m: "M2"}]

A helper function (perhaps not optimum :)

group_assoc = fn list ->
    list
    |> Enum.map(fn {m, c} -> %{m: m, c: c} end)
    # list_maps = [%{m: "M1", c: "C1"}, %{m: "M1", c: "C2"}, %{m: "M2", c: "C3"}]
    |> Enum.group_by(& &1.m)
    |> Enum.map(fn {k, v} ->
      %{m: k, c: Enum.reduce(v, [], fn e, acc -> [e.c | acc] end)}
    end)
  end

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is neededtechnicalA technical issue that requires understanding of the code, infrastructure or dependencies

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions