Chartjs-How can I filter these data per month?

1πŸ‘

βœ…

To get it work you’ll need something like this:

import "./styles.css";
import { Line } from "react-chartjs-2";

export default function App() {
  const data = [
    {
      doses: {
        dose2: true,
        dose1: true,
        selectedVaccine: "AstraZeneca",
        firstDose: { seconds: 1630374445, nanoseconds: 511000000 },
        secondDose: { seconds: 1632966600, nanoseconds: 0 }
      },
      displayName: "Dark",
      address: ""
    },
    {
      address: "",
      doses: {
        firstDose: { seconds: 1630135912, nanoseconds: 920000000 },
        dose2: true,
        selectedVaccine: "AstraZeneca",
        secondDose: { seconds: 1632727920, nanoseconds: 0 },
        dose1: true
      },
      displayName: "Raven"
    }
  ];

  const dosesTemplate = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

  const doses1 = data.reduce(
    (acc, cur) => {
      if (!cur.doses.dose1) return acc;
      const month = new Date(cur.doses.firstDose.seconds * 1000).getMonth();
      acc[month] = acc[month] + 1;

      return acc;
    },
    [...dosesTemplate]
  );

  const doses2 = data.reduce(
    (acc, cur) => {
      if (!cur.doses.dose2) return acc;
      const month = new Date(cur.doses.secondDose.seconds * 1000).getMonth();
      acc[month] = acc[month] + 1;

      return acc;
    },
    [...dosesTemplate]
  );

  return (
    <div className="App">
      <Line
        data={{
          labels: [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
          ],
          datasets: [
            {
              label: "First Dose",
              data: doses1,
              backgroundColor: ["red"],

              borderWidth: 1
            },
            {
              label: "2nd Dose",
              data: doses2,
              backgroundColor: ["orange"]
            }
          ]
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          title: {
            display: true,
            text: "Hello",
            fontSize: 20
          },
          legend: {
            labels: {
              fontSize: 25
            }
          }
        }}
      />
    </div>
  );
}

It is possible to refactor to reduce code duplication πŸ™‚

Leave a comment