I am trying to find index_value for an element in the list which is duplicate
[%{day: "mon", name: "Doc"}, %{day: "mon", name: "Doctor"}, %{day: "mon", name: "Doctor"}, %{day: "wed", name: "Doc"}, %{day: "wed", name: "Doc"}]
I am only concerned about day
.
When I try
list |> Enum.find_index(fn hour -> hour.day == "mon" end)
this gives me 0, where “mon” has 3 items.
I want to get the very last index value, anyhow my main purpose is to get use that index to get the very next value to it.
In this case , I am trying to get
%{day: "wed", name: "Doc"}
any help would be grateful, thank you.
You can do it with Enum.reduce/3
.
You should spend less time thinking about indexes. If the goal is to get the entry in the list that follows the last day of “mon” then here we go:
iex(8)> list = [%{day: "mon", name: "Doc"}, %{day: "mon", name: "Doctor"}, %{day: "mon", name: "Doctor"}, %{day: "wed", name: "Doc"}, %{day: "wed", name: "Doc"}]
[
%{day: "mon", name: "Doc"},
%{day: "mon", name: "Doctor"},
%{day: "mon", name: "Doctor"},
%{day: "wed", name: "Doc"},
%{day: "wed", name: "Doc"}
]
iex(9)> list |> Enum.chunk_every(2, 1, :discard) |> Enum.reverse |> Enum.find_value(fn [%{day: d}, next] -> if d == "mon", do: next end)
%{day: "wed", name: "Doc"}
2 Likes
In case your goal is to find last unique value for data for a particular day, you could do:
iex(4)> a = [%{day: "mon", name: "Doc"}, %{day: "mon", name: "Doctor"}, %{day: "mon", name: "Doctor"}, %{day: "wed", name: "Doc"}, %{day: "wed", name: "Doc2"}]
[
%{day: "mon", name: "Doc"},
%{day: "mon", name: "Doctor"},
%{day: "mon", name: "Doctor"},
%{day: "wed", name: "Doc"},
%{day: "wed", name: "Doc2"}
]
iex(5)> Map.new(a, fn x -> {x.day, x} end)
%{"mon" => %{day: "mon", name: "Doctor"}, "wed" => %{day: "wed", name: "Doc2"}}
iex(6)> Map.new(a, fn x -> {x.day, x} end) |> Map.values()
[%{day: "mon", name: "Doctor"}, %{day: "wed", name: "Doc2"}]
2 Likes