DEV Community

AshikPaul42
AshikPaul42

Posted on • Updated on

How to count occurrences of dates in an array of date ranges: JavaScript

I have a date-range of 01-01-2020 to 31-12-2020 and an array of date-ranges. I want the occurrence of each date in the array vs the main range.

    Eg: mainRange => 01-01-2020 to 31-12-2020

    dateRanges =[
      [01-01-2020, 03-01-2020],
      [03-01-2020, 04-01-2020],
      [03-01-2020, 06-01-2020]
    ];

    the output should be =>

    countArr = [1,1,3,2,1,1,0,0,......,0]; //array length 365

I was desparate and I had posted the same on stackoverflow too. 🥺

SOLUTION :

var range1 = new Date(2020, 0, 1),
    range2 = new Date(2020, 11, 31),
    dateRanges =[
        [new Date(2020, 0, 1), new Date(2020, 0, 3)],
        [new Date(2020, 0, 3), new Date(2020, 0, 4)],
        [new Date(2020, 0, 3), new Date(2020, 0, 6)],
    ],
    result = [];

while (range1 <= range2) {
    var count = 0;
    dateRanges.forEach(
        function(range) {
            if (range1 >= range[0] && range1 <= range[1]) {
                count++;
            }
        }
    );
    result.push(count);
    range1.setDate(range1.getDate() + 1); //+1 day
}

console.log(result);

Thank you 😍

Oldest comments (0)