D
D
dates2021-04-28 14:20:17
JavaScript
dates, 2021-04-28 14:20:17

How to split this array?

There is an array with dates, I need to combine them, but I can’t do it in any way.

Example:

Case 1, Input:

[
  {
    "from":"03/01/2021",
    "to":"03/06/2021"
  },
  {
    "from":"03/10/2021",
    "to":"03/15/2021"
  },
  {
    "from":"03/20/2021",
    "to":"03/25/2021"
  }
]


Output: Mar 1-6, 10-15, 20-25

Case 2, Input:
[
  {
    "from":"03/01/2021",
    "to":"03/05/2021"
  },
  {
    "from":"03/08/2021",
    "to":"03/10/2021"
  },
  {
    "from":"03/07/2021",
    "to":"03/20/2021"
  }
]


Output: Mar 1-5, 7-20

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2021-04-28
@Stalker_RED

As far as I understand, you need to check all ranges for intersections with other ranges.
1. Take the first pair of dates, check if from falls between some other from-to pairs.
      a. If you hit - you found the intersection. take the minimum of both from, the maximum of both to, put in the first range, delete the matched one, repeat the intersection check.
      b. Then the same for the date to.
2. Do the same with the rest of the remaining ranges.
As a result, you will only have non-intersecting ones, and you output them normally anyway.

W
Wataru, 2021-04-28
@wataru

Throw all records into one array and sort by time. It probably makes sense to parse dates into some type of Date, or whatever it is called in js.
Then iterate over the array, maintaining a counter of open intervals. We met "from" - increased the counter. met "to" - reduced.
If the counter was changed from 0 to 1, then the beginning of the segment in the answer is on the current date. If changed from 1 to 0, then that's the end.
Probably, it will be necessary to break the segments into months later.
You also need to figure out when the dates coincide. If there are to and from on the same date, should this be considered one segment? Then, when sorting, put "from" before "to" on the same date (In comparison, if dates are equal, also compare the type of event).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question