Retrieve all the item from a list

I wrote a function called trace_time_spent(entries ,title) where an list of entries data and a title is passed in and return the time difference of in the data if the specific title is matched.

Suppose the entries containing these data:

 [
   %{date: ~D[2018-12-20], id: 3, time: ~T[23:10:00.000], title: "Shopping"},
   %{date: ~D[2018-12-20], id: 4, time: ~T[12:00:07.001], title: "Shopping"},
   %{date: ~D[2018-12-20], id: 4, time: ~T[12:00:07.001], title: "Studying"}
 ]

(There may be more data in the actual working environment)

What I want to do is get all the date and time into a separate list so that I can give them a sort and do some calculation the the maximum difference

They should look like: [ ~D[2018-12-20] ] for day and [ ~T[23:10:00.000], ~T[12:00:07.001] ] for time.

How could I do such an iteration?

Consider a MapSet. You can make two distinct map sets and update them as you iterate through the list of entries.

Good evening @Alfredhana,

Lets say your data exists in the variable data:

data = [
   %{date: ~D[2018-12-20], id: 3, time: ~T[23:10:00.000], title: "Shopping"},
   %{date: ~D[2018-12-20], id: 4, time: ~T[12:00:07.001], title: "Shopping"},
   %{date: ~D[2018-12-20], id: 4, time: ~T[12:00:07.001], title: "Studying"}
 ]

Now, we can use Enum.map/2 to pull the data we want and create a new list:

new_data = data
|> Enum.map(fn %{date: date} -> date end)

You can even get fancy and use some short-hand:

new_data = data
|> Enum.map(&(&1[:date]))

Hope this is what you were looking for.

You can also use Kernel.get_in/2:

get_in(data, [Access.all(), :time])
4 Likes

OIC, any idea for the filtering, like if I only want the data with the shopping title?

You can use Enum.filter/2 for that. To get all entries with the title “Shopping” you would do:

filtered_data = data |> Enum.filter(fn %{title: title} -> title == "Shopping" end) 

You can also combine filtering and @Matt’s example:

new_data = data 
|> Enum.filter(fn %{title: title} -> title == "Shopping" end)
|> Enum.map(fn %{date: date} -> date end)