Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map and group array

I am creating a Rails 3.2 web app and in this app I am collecting and displaying time reports. I have a query that looks like this:

@reports = Timereport.where("backend_user_id = ?", user.id).group("id, date(created_at)").created_between(from, to).order("date(created_at) desc").select("id, date (created_at) as date, sum(total_time) as seconds")

Which outputs this:

[#<Timereport id: 370>, #<Timereport id: 367>, #<Timereport id: 368>, #<Timereport id: 369>]

Each object contains date and seconds which can be accessed like this:

<% @reports.each do |report| %>
 <%= report[:date] %>
 <%= report[:seconds] %>
<% end %>

What I really need to be able to do is to group by days to get total amount of seconds per day:

I tried this:

<% output = @reports.map { |f| [f.date, f.seconds] } %>

Which gave me this result where the dates are seperate. I need to group the dates so that I can get the total amount of seconds per day.

[["2014-06-18", "3600"], ["2014-06-17", "3600"], ["2014-06-17", "3600"], ["2014-06-17", "3600"]]

So in other words. I need this result:

[["2014-06-18", "3600"], ["2014-06-17", "10800"]]

How can I achieve this?

like image 374
Jonathan Clark Avatar asked Oct 25 '25 18:10

Jonathan Clark


1 Answers

You can do it with next code:

@reports.group_by { |x| x.date }.map { |date, record|
  [date, record.map(&:seconds).map(&:to_i).reduce(:+).to_s]
}
like image 115
zishe Avatar answered Oct 27 '25 09:10

zishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!