I am trying to write a function that gets an array of dates (potentially unsorted, date_array) as input and determines the number of consecutive days that are in the array from a certain date (start_date) backwards, not including the start date.
Example:
start_date = 23.01.2023
date_array = [
01.01.2023,
02.01.2023,
20.01.2023, <- day 3 of the streak
21.01.2023, <- day 2 of the streak
22.01.2023, <- day 1 of the streak
22.01.2023, <- day 1 of the streak
23.01.2023,
24.01.2023]
Result:
streak_lenght: 3 days
The function I implemented is supposed to create a date range from the start date backwards and count, how many dates in the array are within the range. Every loop, the end date of the range goes one day further into the past. The loop continues as long as the number of dates within the range grow.
start date … start date – 1 day
start date … start date – days
However, for some reason the start date gets overwritten by the end date before the while loop starts…
I would greatly appreciate any help – or suggestions for better solutions to the problem. Thanks in advance!
const dateArray = [
new Date("2022-12-31"),
new Date("2023-01-02"), // day 3 of streak
new Date("2023-01-03"), // day 2 of streak
new Date("2023-01-03"), // day 2 of streak
new Date("2023-01-04"), // day 1 of streak
new Date("2023-01-05")];
const d_start = new Date("2023-01-05");
function currentStreak(dateArray, d_start) {
// dateArray: Array of dates on which event was executed
// d_start: start date of the streak, not included
// Create a range d_start ... d_end, d_end starts one day before d_start
let d_end = d_start
d_end.setDate(d_start.getDate() - 1)
let countPrev = -1
let count = 0
let streakCount = 0
// Count how many array elements are in the range and continue loop while this number increases
while (count > countPrev) {
countPrev = count
// count number of array elements between start and end date
count = dateArray.reduce((accumulator, currentValue) => {
if((d_start > currentValue) && (currentValue > d_end))
{
accumulator += 1
}
return accumulator
}, 0)
// set new end date for next iteration
d_end = d_end.setDate(d_end.getDate() - 1)
streakCount = streakCount+1
}
return count;
}
currentStreak(dateArray, d_start)