How to hide row in chartJS when filtering?

2👍

This can be done using the Plugin Core API. It offers different hooks that can be used to perform custom code.

  1. The labels and data need to be defined outside the chart configuration.
  2. In the beforeUpdate hook, you set the initial labels and data to the chart configuration.
  3. In the beforeElementsUpdate hook you remove individual labels and corresponding data values from the chart configuration if all values for a certain label are null or if the dataset is hidden.

Please take a look at below runnable sample and see how it works.

const labels = ['A', 'B', 'C'];
const data = [
  [10, null, 4],
  [9, null, 8],
  [3, 5, 8]
];

new Chart('chart', {
  type: 'bar',
  plugins: [{
    beforeUpdate: chart => {
      chart.data.labels = labels;
      chart.data.datasets.forEach((ds, i) => ds.data = data[i]);
    },
    beforeElementsUpdate: chart => {         
      let sums = labels.map((l, i) => chart.data.datasets.reduce((prev, ds, iDs) => prev + (chart.getDatasetMeta(iDs).hidden ? 0 : ds.data[i]), 0));
      chart.data.labels = labels.filter((l, i) => sums[i]);
      chart.data.datasets.forEach((ds, iDs) => ds.data = data[iDs].filter((v, i) => sums[i]));
    }
  }],
  data: {
    datasets: [{
        label: 'Dataset 1',
        backgroundColor: 'red'
      },
      {
        label: 'Dataset 2',
        backgroundColor: 'blue'
      },
      {
        label: 'Dataset 3',
        backgroundColor: 'green'
      }
    ]
  },
  options: {
    indexAxis: 'y',
    scales: {
      x: {
        stacked: true
      },
      y: {
        stacked: true
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<canvas id="chart" height="80"></canvas>

Leave a comment