I’m trying to Loop through an array and pull out the closest/next meeting object Chronologically.
Each object has a Start and End time but I want to know what is the current event OR the next event that’s going to happen. Failing that to get the last event.
e.g.
JavaScript
x
16
16
1
const meetings = [{title:"morning",startAt:new Date("2020-10-14 7:00"),
2
endAt:new Date("2020-10-14 8:00")},
3
{title:"evening",startAt:new Date("2020-10-14 20:00"),
4
endAt:new Date("2020-10-14 21:00")},
5
{title:"afternoon",startAt:new Date("2020-10-14 15:00"),
6
endAt:new Date("2020-10-14 15:12")}]
7
// results:
8
"2020-10-14 01:00" // morning
9
"2020-10-14 07:30" // morning
10
"2020-10-14 08:01" // afternoon
11
"2020-10-14 15:00" // afternoon
12
"2020-10-14 15:12" // afternoon
13
"2020-10-14 15:13" // evening
14
"2020-10-14 21:00" // evening
15
"2020-10-14 23:59" // evening
16
This is what i have so far:
JavaScript
1
13
13
1
const targetDate = new Date("2020-10-14 15:12")
2
3
meetings.reduce((found,meeting)=>{
4
if( ! found){
5
return meeting
6
} else if( meeting.startAt > targetDate
7
&&( found.startAt < targetDate
8
|| meeting.startAt < found.startAt)){
9
return meeting
10
}
11
return found
12
},{}))
13
Advertisement
Answer
Try this function getMeeting(meetings,targetDate)
You can pass the set of meetings + a target Date/defaults to now
JavaScript
1
48
48
1
const testSet = [
2
[new Date("2020-10-14 01:00"),"morning"],
3
[new Date("2020-10-14 07:30"),"morning"],
4
[new Date("2020-10-14 08:01"),"afternoon"],
5
[new Date("2020-10-14 15:00"),"afternoon"],
6
[new Date("2020-10-14 15:12"),"afternoon"],
7
[new Date("2020-10-14 15:13"),"evening"],
8
[new Date("2020-10-14 21:00"),"night"],
9
[new Date("2020-10-14 23:59"),"night"],
10
]
11
12
const meetings = [
13
{ title: "morning", startAt: new Date("2020-10-14 7:00"), endAt: new Date("2020-10-14 8:00") },
14
{ title: "evening", startAt: new Date("2020-10-14 20:00"), endAt: new Date("2020-10-14 20:59") },
15
{ title: "afternoon", startAt: new Date("2020-10-14 15:00"), endAt: new Date("2020-10-14 15:12") },
16
{ title: "night", startAt: new Date("2020-10-14 21:00"), endAt: new Date("2020-10-14 23:15") },
17
];
18
19
20
function getMeeting(meetings, targetDate = new Date()){
21
22
return meetings.sort((a,b)=>b.startAt - a.startAt)
23
.reduce((closest, meeting) => {
24
25
if ( ! closest) {
26
closest = meeting;
27
} else if (closest.startAt <= targetDate
28
&& closest.endAt >= targetDate) {
29
// KEEP closest
30
} else if (meeting.startAt <= targetDate
31
&& meeting.endAt >= targetDate) {
32
closest = meeting;
33
} else if (meeting.startAt <= targetDate
34
&& closest.startAt <= meeting.startAt) {
35
closest = meeting;
36
} else if (meeting.endAt >= targetDate
37
&& closest.endAt >= meeting.endAt) {
38
closest = meeting;
39
}
40
41
return closest;
42
}, null);
43
}
44
45
testSet.forEach(([date,name])=>{
46
console.log(name === getMeeting(meetings,date).title ? "✔" : "✘", date)
47
})
48