DEV Community

AshikPaul42
AshikPaul42

Posted on β€’ Edited on

2 3

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 😍

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay