Skip to content

Instantly share code, notes, and snippets.

@jevin
Last active September 20, 2021 04:25
Show Gist options
  • Save jevin/b045a18b633c3c1a9d4a7743fcb69a33 to your computer and use it in GitHub Desktop.
Save jevin/b045a18b633c3c1a9d4a7743fcb69a33 to your computer and use it in GitHub Desktop.
Removes dates within X seconds of each other in an array
require 'date'
def remove_similar_dates(dates, delta=3)
dates.map!{ |date| date.strftime("%s").to_i }.sort!
for index_1 in (0..dates.size) do
item_1 = dates[index_1]
if item_1 != nil
marked = []
dates.each_with_index do |item_2, index_2|
if (item_1 - item_2).abs <= delta && index_1 != index_2
marked << item_2
end
end
marked.map{ |item| dates.delete(item) }
end
end
dates.map!{ |date| DateTime.strptime(date.to_s, "%s") }
end
dates = [
DateTime.parse("2021-05-15 08:29:00"),
DateTime.parse("2021-05-15 08:30:12"),
DateTime.parse("2021-05-15 08:30:14"),
DateTime.parse("2021-05-15 08:31:00"),
DateTime.parse("2021-05-16 08:31:00"),
DateTime.parse("2021-05-15 08:30:10"),
DateTime.parse("2021-05-14 08:29:00"),
DateTime.parse("2021-05-15 08:30:13"),
DateTime.parse("2021-05-15 08:30:11"),
]
puts remove_similar_dates(dates)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment