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

How to fill in missing values in a reduce function

I’m trying to create a stacked bar graph where I count the categories per month

The data coming from the backend is similar to this:

[
    {date: 'January', category: 'A'},
    {date: 'January', category: 'B'},
    {date: 'February', category: 'A'},
    {date: 'February', category: 'B'},
    {date: 'February', category: 'B'},
    {date: 'March', category: 'C'},
    {date: 'March', category: 'A'},
    {date: 'April', category: 'C'},
    ...
]

With help, I’ve managed to count the different categories and group the data into their respective months like the shape below:

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

[
    {date: 'January', countA: 1, countB: 1, countC: 0},
    {date: 'February', countA: 1, countB: 2, countC: 0},
    {date: 'March', countA: 1, countB: 0, countC: 1},
    ...
]

However, this only produces the data whenever the month exists. So if there is no data for the month of, say, June, there won’t be any object with the name: 'June'.

I need to have these missing values filled with the corresponding month and with the count values to zeros

>Solution :

Once data is ready with missing months only, fill in missing entries with Array.map

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

const dataWithMissingMonths = [    {date: 'January', countA: 1, countB: 1, countC: 0},    {date: 'February', countA: 1, countB: 2, countC: 0},    {date: 'March', countA: 1, countB: 0, countC: 1} ];

const result = months.map(m => dataWithMissingMonths.find(data => data.date === m)?? {date: m, countA: 0, countB: 0, countC: 0});

console.log(result);
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