I have a sorted array full of objects which I'd like to group by comparing them to their surrounding elements.
a is sorted by the start attribute.
a = [{ name: "joe", start: "9am", end: "10am" },
{ name: "joe", start: "10am", end: "11am" },
{ name: "harry", start: "11am", end: "12pm" },
{ name: "harry", start: "12pm", end: "1pm" },
{ name: "harry", start: "2pm", end: "3pm" },
{ name: "joe", start: "3pm", end: "4pm" },
{ name: "joe", start: "4pm", end: "5pm" }]
I would like to group adjacent objects by the name attribute but only if the start and end times are the same, producing:
a = [[{ name: "joe", start: "9am", end: "10am" }, { name: "joe", start: "10am", end: "11am" }],
[{ name: "harry", start: "11am", end: "12pm" }, { name: "harry", start: "12pm", end: "1pm" }],
[{ name: "harry", start: "2pm", end: "3pm" }],
[{ name: "joe", start: "3pm", end: "4pm" }, { name: "joe", start: "4pm", end: "5pm" }]]
There is no maximum to the amount of consecutive time periods.
I can group them by name if adjacent as seen here: Ruby / Rails Groups only Adjacent Array Elements
a.chunk { |hash| hash[:name] }.map(&:last)
But it doesn't appear as though I can get the element index with chunk to do the start end time comparisons.
It looks like the answer is here: Grouping an array by comparing 2 adjacent elements
But I'm failing miserably at writing my own function. (I'm struggling to understand what slice_before does.)
def self.group_by(data)
tmp = data.first
data.slice_before do |item|
tmp, prev = item, tmp
item.application == prev.application &&
item.start == prev.end
end.to_a
return data
end
Any help would be appreciated!