Sample algorithm:
Sort all objects by the start date of the time segment. Form a new structure by looping through the sorted structure according to the algorithm: 2.1. Outside the loop, prepare a variable for a temporary object where intersecting time intervals will be accumulated. As well as an array where intersecting segments will be accumulated. Record the first time segment in it. The cycle starts from the second time period. 2.2. Check whether the current time segment “intersects” with the next one. In other words, the beginning of the next date is less than the end of the current one. 2.2.1. If it intersects, then update the end in the time structure with the end of the next segment. 2.2.2 If they do not intersect, then push into the result array. And add the following time period to the accumulation variable. The loop continues for the segment after the next (although everything will work if this is not done).
const data = [ { "from":"01/01/2020", "to":"01/06/2020" }, { "from":"01/10/2020", "to":"01/10/2020" } ]
const monthToString = month => {
const months = {
'01': 'Jan',
'02': 'Feb',
'03': 'Mar',
'04': 'Apr',
'05': 'May',
'06': 'Jun',
'07': 'Jul',
'08': 'Aug',
'09': 'Sep',
'10': 'Oct',
'11': 'Nov',
'12': 'Dec',
}
return months[month] || month
}
const result = Object.entries(data.reduce((res, {from, to}) => {
const [monthFrom, day, year] = from.split('/')
const [m, dayTo, y] = to.split('/')
const month = monthToString(m)
return {
...res,
[month]: [...(res[month] || []), [day, dayTo]]
}
}, {})).map(([month, days]) => `${month} ${days.map(([from, to]) => `${parseInt(from)}-${parseInt(to)}`).join(', ')}`).join('\n')
console.log(result)
How to Combine dates when they intersect?