从日期集合中选择每个月的最后日期

时间:2022-07-27 11:50:16

In Ruby on Rails I have a collection of data which needs to be filtered to get the most recently created ones of each month. What is the best optimized way to do this?

在Ruby on Rails中,我有一组数据需要过滤才能获得每月最新创建的数据。这样做的最佳方法是什么?

e.g

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]

result should be

结果应该是

["2012-1-18, "2012-2-23", ..]

4 个解决方案

#1


2  

def last_in_month(dates)
  dates = dates.map {|date_string| Date.parse(date_string)}
  grouped_by_month = dates.group_by {|date| date.month}
  grouped_by_month.map do |month, dates_in_month|
    dates_in_month.max_by {|d| d.day}
  end
end

last_in_month(your_nested_arrays.flatten)

Returns dates objects.

返回日期对象。

Transform to strings again :)

再次转换为字符串:)

last_in_month(your_nested_arrays.flatten).map {|d| d.to_s(:db)}

#2


1  

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
.group_by{|s| s[/\d+-\d+/]}
.values
.map{|a| a.max_by{|s| s[/\d+\z/].to_i}}

#3


0  

This should work:

这应该工作:

my_date = ["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
my_date.sort_by{|date| month,day,year=date.split("-");[year,month,day]}

But if these dates are coming out of a database table, maybe you could consider sorting it there. That would be a bit faster (especially if there are many records).

但是如果这些日期来自数据库表,也许你可以考虑在那里进行排序。那会更快一点(特别是如果有很多记录)。

#4


0  

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"].map { |d| Date.parse(p) }.sort.group_by { |d| [d.month, d.year].join('/') }.map { |k,v| v.last.strftime("%Y-%-m-%-d") }

#1


2  

def last_in_month(dates)
  dates = dates.map {|date_string| Date.parse(date_string)}
  grouped_by_month = dates.group_by {|date| date.month}
  grouped_by_month.map do |month, dates_in_month|
    dates_in_month.max_by {|d| d.day}
  end
end

last_in_month(your_nested_arrays.flatten)

Returns dates objects.

返回日期对象。

Transform to strings again :)

再次转换为字符串:)

last_in_month(your_nested_arrays.flatten).map {|d| d.to_s(:db)}

#2


1  

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
.group_by{|s| s[/\d+-\d+/]}
.values
.map{|a| a.max_by{|s| s[/\d+\z/].to_i}}

#3


0  

This should work:

这应该工作:

my_date = ["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
my_date.sort_by{|date| month,day,year=date.split("-");[year,month,day]}

But if these dates are coming out of a database table, maybe you could consider sorting it there. That would be a bit faster (especially if there are many records).

但是如果这些日期来自数据库表,也许你可以考虑在那里进行排序。那会更快一点(特别是如果有很多记录)。

#4


0  

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"].map { |d| Date.parse(p) }.sort.group_by { |d| [d.month, d.year].join('/') }.map { |k,v| v.last.strftime("%Y-%-m-%-d") }