Chartjs-Part 2 – how to group duplicate labels in order to create a label without duplicates in chart.js

0👍

You can get a Month array and append the dataset data based on the index in the Month Array.

Example below

var trendMensuel = [
  { produit: "HOME40Z", mois: "Janvier", effectif: 1, bgColor: "red" },
  { produit: "HOME60", mois: "Janvier", effectif: 2, bgColor: "green" },

  { produit: "HOME40Z", mois: "Février", effectif: 3, bgColor: "red" },
  { produit: "PRO", mois: "Février", effectif: 4, bgColor: "blue" },

  { produit: "HOME60", mois: "Mars", effectif: 5, bgColor: "green" },
];

const months = trendMensuel.reduce((a, b) => {
  const i = a.findIndex(x => x === b.mois);
  if (i === -1) {
    a.push(b.mois);
  }
  return a;
}, []);

const lenOfMonth = months.length;

const products = trendMensuel.reduce((a, b) => {
  const i = months.findIndex(y => y === b.mois);
  const j = a.findIndex(y => y.label === b.produit);

  if (j === -1) {
    const obj = {
      type: "bar",
      backgroundColor: b.bgColor,
      borderColor: "rgba(54, 162, 235, 1)",
      borderWidth: 1,
      label: b.produit,
      data: new Array(lenOfMonth).fill(0),
    };
    obj.data[i] = b.effectif;
    a.push(obj);
  } else {
    a[j].data[i] = b.effectif;
  }

  return a;
}, []);

var ctx = document.getElementById("trendmensuel").getContext("2d");
var chart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: months, // ito efa mety
    datasets: products,
  },
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.4.1/dist/chart.min.js"></script>
<canvas id="trendmensuel" width="400" height="400"></canvas>

Leave a comment