Chartjs-Chart.js line chart: gap between December and January

0👍

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)

Leave a comment