Reputation: 2598
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.
Upvotes: 2
Views: 317
Reputation: 121000
There is no such thing as index for linked lists. Linked lists are not arrays.
If you are trying to get to the next value after a bunch of %{day: "mon"}
, you might want to reduce
Enum.reduce_while(input, :before, fn
%{day: "mon"}, _ -> {:cont, :in}
result, :in -> {:halt, result}
end)
#⇒ %{day: "wed", name: "Doc"}
or, which is arguably more readable, but less performant, Enum.chunk_every/4
in combination with Enum.find/2
input
|> Enum.chunk_every(2, 1, :discard)
|> Enum.find(&match?([%{day: "mon"}, %{day: day}] when day != "mon", &1))
#⇒ [%{day: "mon", name: "Doctor"}, %{day: "wed", name: "Doc"}]
The second/last element of the array returned is the result.
Upvotes: 2