Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Start a new ID every time the date changes in an array of objects

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading