Skip to content Skip to sidebar Skip to footer

Generate Bar Chart Using Chart.js And Associative Array

I have associative array and I want to display it using Chart.JS library. My Array: array:4 [▼ 0 => array:3 [▼ 'faculty' => 'Information Technology' 'category

Solution 1:

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 sortconst faculties = [...newSet(data.map(v => v['faculty']))].sort();

// this will get distinct category and sortconst categories = [...newSet(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');

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

I created a jsfiddle to show the code running.

Post a Comment for "Generate Bar Chart Using Chart.js And Associative Array"