Search code examples
javascriptarrayschart.jsassociative-array

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" => "ELearning"
    "counter" => 2
  ]
  1 => array:3 [▼
    "faculty" => "Information Technology"
    "category" => "Webex"
    "counter" => 2
  ]
  2 => array:3 [▼
    "faculty" => "Masscom"
    "category" => "ELearning"
    "counter" => 3
  ]
  3 => array:3 [▼
    "faculty" => "Masscom"
    "category" => "Webex"
    "counter" => 3
  ]
]

What I am trying to do:

I am trying to show: - Faculties at the bottom as labels - For each faculty I want to show all the category and its counter

e.g.:

1) Information Technology has category ELearning with value 2 and has category Webex with value 2

2) Masscom has category ELearning with value 3 and has category Webex with value 3

JS Code:

var faculties = ['Information Technology', 'Masscom'];
var f = document.getElementById("mybarChart");
new Chart(f, {
    type: "bar",
    data: {
       labels: faculties,
       datasets: ....
    },
})

Solution

  • 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.