Consider this array of plans:
[
{ _id: "1", project_id: "1", day: "2021-03-02" },
{ _id: "2", project_id: "1", day: "2021-03-01" },
{ _id: "3", project_id: "1", day: "2021-03-03" },
{ _id: "4", project_id: "2", day: "2021-03-01" },
{ _id: "5", project_id: "1", day: "2021-03-04" },
{ _id: "6", project_id: "1", day: "2021-03-10" }
]
The goal is to calculate the consecutive number of days (excluding weekends) for plans with the same project ID. Based on this data, the desired output should be:
[
{ _id: "1", project_id: "1", day: "2021-03-02", count: 4 },
{ _id: "2", project_id: "1", day: "2021-03-01", count: 4 },
{ _id: "3", project_id: "1", day: "2021-03-03", count: 4 },
{ _id: "4", project_id: "2", day: "2021-03-01", count: 1 },
{ _id: "5", project_id: "1", day: "2021-03-04", count: 4 },
{ _id: "6", project_id: "1", day: "2021-03-10", count: 1 }
]
An attempted solution yielded the same count for all plans with the same project ID:
let plans = [
{ _id: "1", project_id: "1", day: "2021-03-02" },
{ _id: "2", project_id: "1", day: "2021-03-01" },
{ _id: "3", project_id: "1", day: "2021-03-03" },
{ _id: "4", project_id: "2", day: "2021-03-01" },
{ _id: "5", project_id: "1", day: "2021-03-04" },
{ _id: "6", project_id: "1", day: "2021-03-10" }
];
plans.filter(p => new Date(p.day).getDay() !== 6 && new Date(p.day).getDay() !== 0).map((plan, i, arr) => {
let count = 1;
arr
.filter(p2 => plan.project_id === p2.project_id)
.sort((a, b) => new Date(a.day).getTime() - new Date(b.day).getTime())
.map((plan3, k, arr3) => {
if (k > 0) {
let tmpDate = new Date(arr3[k - 1].day);
if (tmpDate.getDay() === 5) {
tmpDate.setDate(tmpDate.getDate() + 3);
} else {
tmpDate.setDate(tmpDate.getDate() + 1);
}
if (tmpDate.getTime() === new Date(plan3.day).getTime()) {
count++;
}
}
});
plan.count = count;
})
console.log(plans);