I have an array of objects that looks like the following
[
{ id: 332, tech: 'bob', Date: '2022-07-25', dateID: 0 },
{ id: 342, tech: 'bob', Date: '2022-07-25', dateID: 1 },
{ id: 344, tech: 'bob', Date: '2022-07-26', dateID: 2 },
{ id: 335, tech: 'bob', Date: '2022-07-26', dateID: 3 },
{ id: 334, tech: 'bob', Date: '2022-07-29', dateID: 4 }
]
What I am trying to do is create an array of objects, so that everyTime [i].Date changes dateId starts back at 0 and increments like the following:
[
{ id: 332, tech: 'bob', Date: '2022-07-25', dateID: 0 },
{ id: 342, tech: 'bob', Date: '2022-07-25', dateID: 1 },
{ id: 344, tech: 'bob', Date: '2022-07-26', dateID: 0 },
{ id: 335, tech: 'bob', Date: '2022-07-26', dateID: 1 },
{ id: 335, tech: 'bob', Date: '2022-07-26', dateID: 2 },
{ id: 334, tech: 'bob', Date: '2022-07-29', dateID: 0 }
]
I have tried reducing the array of objects so I had an object with the date and how many times it occurs and using a nested for loop but that didn’t seem to work and I cant get it with array.map.
>Solution :
Here’s another approach. Essentially what I’m doing grabbing the previously iterated item. Then I check whether the Date of the current item does not equal the Date of the previous one. If that is the case the new dateID is set to 0. If the Date is still the same the dateID will be increased.
const data = [
{ id: 332, tech: "bob", Date: "2022-07-25", dateID: 0 },
{ id: 342, tech: "bob", Date: "2022-07-25", dateID: 1 },
{ id: 344, tech: "bob", Date: "2022-07-26", dateID: 2 },
{ id: 335, tech: "bob", Date: "2022-07-26", dateID: 3 },
{ id: 334, tech: "bob", Date: "2022-07-29", dateID: 4 },
];
const output = data.reduce((acc, curr, i) => {
const prev = acc[i - 1];
return [
...acc,
{
...curr,
dateID: prev?.Date !== curr.Date ? 0 : prev?.dateID + 1,
},
];
}, []);
console.log(output);
.as-console-wrapper {
min-height: 100% !important;
}