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:
[
{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);