Chartjs-Generate bar chart using chart.js and associative array

2👍

Essentially, you will need a data set for each of your categories. Each data set will need a data entry for each faculty.

Using the code below, you will get a chart that looks like this:

chart from JS fiddle code

// this will get distinct faculty and sort
const faculties = [...new Set(data.map(v => v['faculty']))].sort();

// this will get distinct category and sort
const categories = [...new Set(data.map(v => v['category']))].sort();

const datasets = categories.map(category => ({
  label: category,
  data: faculties.map(faculty => {
    const value = data.find(v => v['faculty'] === faculty && v['category'] === category);

    return value['counter'];
  })
}));

const canvas = document.getElementById('mybarChart');

new Chart(canvas, {
  type: 'bar',
  data: {
    labels: faculties,
    datasets: datasets
  }
});

I created a jsfiddle to show the code running.

Leave a comment