@tot_sat = @sat.group_by do |s|
(time - s["created_at"]).to_i / 1.day
end.select do |diff, _|
diff < 8
end.sort_by do |diff, _|
- diff
end.map do |_, entries|
entries.count
end
This solution groups the entries by the number of days difference from time
, and then counts how many entries are in each day difference.
Update
The code above has a problem if not all the values (0-7) have entries. In this case, the array will be shorter. To avoid that, we'll use a different tactic in translating the grouped hash into the array:
grouped_sat = @sat.group_by do |s|
(time - s["created_at"]).to_i / 1.day
end
@tot_sat = (0..7).map { |days| (grouped_sat[days] || []).count }
In this tactic, all values between 0 and 7, in turn, count the number of elements with the queried interval, defaulting at 0
(the length of the empty array), in the case there were no elements with the queried interval.