使用chart.js和关联数组生成条形图

时间:2019-04-13 01:59:59

标签: javascript arrays chart.js associative-array

我有关联数组,我想使用Chart.JS库显示它。

  

我的阵列:

inet6_ifaddr
  

我正在尝试做的事情:

我试图证明: -底部的学院作为标签 -我想为每个教师显示所有类别及其计数器

例如:

1)信息技术具有类别值为2的电子学习,并且具有类别值为2的Webex

2) Masscom 具有类别值为3的电子教学,并且具有类别值为3的

  

JS代码:

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
  ]
]

1 个答案:

答案 0 :(得分:1)

本质上,您将需要每个类别的数据集。每个数据集都需要为每个教员输入一个数据。

使用下面的代码,您将获得一个如下所示的图表:

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
  }
});

我为show the code running创建了一个jsfiddle。