I have a line chart, which shows monthly dynamics of cumulative data
over the years, which starts from 0 each year.
How to make a gap between December and January for each year? In other words, how to connect dots only if the value increases?
There is an option to add null data and use spangaps
, but that's the last option.
CodePudding user response:
You can search for minimum and maximum date and create a dictionary with all available date and for non-available data you can set it to null
const data = [
{
date: "2019-12-01T00:00:00",
value: "50",
},
{
date: "2020-01-01T00:00:00",
value: "10",
},
];
const dataDates = data.map(({ date, ...rest }) => ({ ...rest, date: new Date(date) }));
const minDate = Math.min(...dataDates.map(({ date }) => date.getTime()));
const maxDate = Math.max(...dataDates.map(({ date }) => date.getTime()));
const dataDictionary = dataDates.reduce((acc, { date, ...rest }) => {
const dateKey = date.getTime();
acc[dateKey] = { date, ...rest };
return acc;
}, {});
const chartJsData = [];
let currentDate = minDate;
while (currentDate <= maxDate) {
if (dataDictionary[currentDate])
chartJsData.push(dataDictionary[currentDate]);
else
chartJsData.push({ date: new Date(currentDate), value: null });
// Increment date with 1 month
currentDate = currentDate 1000 * 60 * 60 * 24 * 30;
}
console.log(chartJsData)