How can I filter the list of dates to list of month in elixir?

Viewed 298

I have a list of dates and correspond to that is the number of sales per month. So What I want is instead of dates I want is to filter out by month.

This is my input

  ["2019-01-01", "900"],
  ["2019-01-01", "150"],
  ["2019-01-01", "150"],
  ["2019-01-01", "450"],
  ["2019-01-01", "180"],
  ["2019-01-01", "240"],
  ["2019-01-01", "300"],

The output I want is:-

  ["2019-01-01 to 2019-01-31", "total sale of this month only"],
  ["2019-02-01 to 2019-02-28", "total sale of this month only"],

Now what I want is to list the array not only of a particular date and the sale on that day. I want to something like above which will give me the month and sale of that month.

month_sales = record
            |> Enum.filter(fn
                ["Date" | _ ] -> false
              _ -> true
            end)
            |> Enum.map(fn [head | tail ]-> [head, Enum.reduce(Enum.take(tail, -1), fn price, acc ->
                acc + price
             end)] end)
            |> IO.inspect()
  1. So first I want to list this not by date but by month.

Help me If anyone knows about this

1 Answers

What I assume you want is a list of all values for a specific month in a specific year. I slightly modified your input to include cases where the year or month is different:

data = [
  ["2019-01-01", "900"],
  ["2019-01-01", "150"],
  ["2019-01-01", "150"],
  ["2019-01-01", "450"],
  ["2019-01-01", "180"],
  ["2018-01-01", "240"],
  ["2019-02-01", "300"]
]

I think the cleanest way to achieve this is to parse this first into appropriate data structures, and then use Enum.group_by to group by {year, month} pairs.

data
|> Enum.map(fn [date, value] ->
  # This is the part that parses it into a representation that's easier to work with
  [Date.from_iso8601!(date), String.to_integer(value)]
end)
|> Enum.group_by(
  # This is the key function - the items will be grouped by this
  fn [date, _value] -> {date.year, date.month} end,
  # This is the value function - it will gather the results of this function under the keys
  fn [_date, value] -> value end
)

This results in:

%{
  {2018, 1} => [240],
  {2019, 1} => [900, 150, 150, 450, 180],
  {2019, 2} => [300]
}

So you can get the list of values for a specific month (January 2019 in this case) with:

Map.get(result, {2019, 1}) # => [900, 150, 150, 450, 180]

Or if you want a sum:

Map.get(result, {2019, 1}) |> Enum.sum() # => 1830
Related