Is there a way to combine objects in an array if a specific condition is met? Specifically, I need to merge the start time and end time from objects in the array.
Here is an example array:
[
{id: 909, room: "room1", name: "end", timestamp: '10:00'},
{id: 908, room: "room1", name: "start", timestamp: '09:00'},
{id: 907, room: "room1", name: "end", timestamp: '08:00'},
{id: 906, room: "room1", name: "start", timestamp: '07:00'},
]
From the above array, I want to pair up the objects where name: "end"
is followed by name:start
. The resulting array should be:
[
{room: "room1", endTimestamp: '10:00', startTimetamp: '09:00'},
{room: "room1", endTimestamp: '08:00', startTimetamp: '07:00'},
]
There may be cases where the array starts with name:start
and doesn't have its end time yet, like this:
[
{id: 910, room: "room1", name: "start", timestamp: '11:00'},
{id: 909, room: "room1", name: "end", timestamp: '10:00'},
{id: 908, room: "room1", name: "start", timestamp: '09:00'},
{id: 907, room: "room1", name: "end", timestamp: '08:00'},
{id: 906, room: "room1", name: "start", timestamp: '07:00'},
]
In this case, the resulting array should be:
[
{ room: "room1", endTimestamp: null, startTimetamp: '11:00'},
{ room: "room1", endTimestamp: '10:00', startTimetamp: '09:00'},
{ room: "room1", endTimestamp: '08:00', startTimetamp: '07:00'},
]
Appreciate your help!