lapinkoira
lapinkoira

Reputation: 8998

Merge Enum.map response in a single list

In the following example I Enum.map a list and depending on some conditions I can receive a single item or a list of items. If I just receive a single item I will end having a list. But if I also receive another list, I end having a nested list.

defmodule TestQuery do

  def build_query() do
    Enum.map(["test1", "test2", "hello"], fn item ->
      query(item)
    end)
  end

  def query(item) do
    case String.contains? item, "test" do
      true -> 1
      false -> [2, 3]
    end
  end

end

iex(2)> TestQuery.build_query
[1, 1, [2, 3]]

How can I merge that list output on false to have a single list? [1, 1, 2, 3]

Think about it as in true I query one item and in false I query multiple items but I want to join them on the same list.

Upvotes: 0

Views: 475

Answers (1)

sobolevn
sobolevn

Reputation: 18090

Refactor your build_query/0 to look like so:

def build_query() do
  ["test1", "test2", "hello"] # this is a style change only
  |> Enum.map(fn item -> query(item) end)
  |> List.flatten # here's the thing that make this list flat
end

See docs on List.flatten: https://hexdocs.pm/elixir/List.html#flatten/1

Upvotes: 2

Related Questions