Filtering list of lists

I am having a list of lists and i want to obtain an output by filtering them.

list =
[
  [[key: 1, value: 2], [key: 1, value: 2]],
  [[key: 1, value: 2], [key: 2, value: 3]],
  [[key: 2, value: 3], [key: 1, value: 2]],
  [[key: 2, value: 3], [key: 2, value: 3]]
]

here In each list i want to filter out those values where the keys are equal.

For example, in first list we have

[[key: 1, value: 2], [key: 1, value: 2]]

here both keys are equal, so how can we filter only those results where both the keys are equal.

Thanks

Hey @owaisqayum what have you tried so far?

I have tried Enum.filter with Enum.map but it didn’t worked. Actually the issue that am facing is that at the same time how can I compare two different lists.

So i have worked on it and found the solution for it

defmodule J do
  def join(list_of_lists) do
    join_single_row(list_of_lists, [])
    |> Enum.map(fn row -> List.flatten(row) end)
  end

  def join_single_row([], final), do: final

  def join_single_row([row | rest_of_rows], final) do
    length =
      Enum.map(row, fn [key, _value] -> key end)
      |> Enum.uniq()
      |> length()

    case length do
      1 ->
        join_single_row(rest_of_rows, final ++ [row])

      _ ->
        join_single_row(rest_of_rows, final)
    end
  end
end

Using Enum.map with Enum.filter would have worked too…

Please note that [key: :value] is a Keyword list… a special kind of list.

:golf: :grin:

iex(5)> list =
...(5)> [
...(5)>   [[key: 1, value: 2], [key: 1, value: 2]],
...(5)>   [[key: 1, value: 2], [key: 2, value: 3]],
...(5)>   [[key: 2, value: 3], [key: 1, value: 2]],
...(5)>   [[key: 2, value: 3], [key: 2, value: 3]]
...(5)> ]

iex(6)> for [left, right] = row <- list, left[:key] == right[:key], do: row
[
  [[key: 1, value: 2], [key: 1, value: 2]],
  [[key: 2, value: 3], [key: 2, value: 3]]
]
2 Likes