Chartjs-Angular 9 Chart.js stacked bar chart with multiple bars

1👍

Compare to the previous answer I have written, the concept is similar.

For the subLabels, since you need to group the data by operatorName and subLabel, you need to distinct the group for the objects containing these 2 properties.

While in the dataset of each object in subLabelDatasets, you can find the value by getting the value based on label, operatorName, and subLabel from the data array.

let labels = [...new Set(data.map((x) => x.label))];
let subLabels = data.reduce((acc, cur: any) => {
  if (
    acc.findIndex(
      (x) =>
        x.operatorName == cur.operatorName && x.subLabel == cur.subLabel
    ) == -1
  )
    acc.push({ operatorName: cur.operatorName, subLabel: cur.subLabel });

  return acc;
}, [] as { operatorName: string; subLabel: string }[]);

let subLabelDatasets = subLabels.map((x) => {
  let datasets = [];

  for (let label of labels) {
    datasets.push(
      data.find(
        (y) =>
          y.label == label &&
          y.subLabel == x.subLabel &&
          y.operatorName == x.operatorName
      )?.count || 0
    );
  }

  return {
    label: x.operatorName + ' ' + x.subLabel,
    data: datasets,
    stack: x.operatorName,
    type: 'bar',
  };
});

this.barChartLabels = labels;
this.barChartData = subLabelDatasets;

Demo @ StackBlitz

Leave a comment