Skip to content

Instantly share code, notes, and snippets.

@tetiana12345678
Last active September 8, 2016 12:10
Show Gist options
  • Save tetiana12345678/72bff083753e3bc551356ef7cdd36ae5 to your computer and use it in GitHub Desktop.
Save tetiana12345678/72bff083753e3bc551356ef7cdd36ae5 to your computer and use it in GitHub Desktop.
I have a challenge of transforming the data from 1 state to another. I have written my implementation, but I know it could be done, just could’t figure it out. I was looking into using Streams, but struggling to implement it. Any suggestions?
input = [["foo", 56, "0", "1"],
["bar", 34, "2", "3"],
["bla", 90, "2", "1"],
["hey", 10, "4", "1"]]
output = [%{"0" => [56]},
%{"2" => [90, 34]},
%{"4" => [10]}
]
input
|> Enum.group_by(fn([_col1, _col2, col3, _col4]) -> col3 end)
|> Enum.map(&extract_col_2_values/1)
defp extract_col_2_values({col3, data}) do
col2_values_sorted_by_col4 =
data
|> Enum.sort_by(fn ([_col1, _col2, _col3, col4]) ->
String.to_integer(col4)
end)
%{col3 => Enum.map(col2_values_sorted_by_col4, fn([_col1, col2, _col3, _col4]) -> col2 end) }
end
@josevalim
Copy link

input
|> Enum.map(fn [_, col2, col3, col4] -> {col3, String.to_integer(col4), col2} end)
|> Enum.sort()
|> Enum.chunk_by(&elem(&1, 0))
|> Enum.map(fn entries ->
  {key, _, _} = hd(entries)
  %{key => Enum.map(entries, &elem(&1, 2))}
end)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment