0👍
✅
This function will return the data you need for ChartJS:
function getCountData(choices, results) {
var counts = {};
var data = [];
choices.forEach(function(c) {
counts[c] = 0;
});
results.forEach(function(r) {
counts[r] += 1;
});
Object.keys(counts).forEach(function(c) {
data.push(counts[c]);
});
return data;
}
var choices = ['Answer1', 'Answer2', 'Answer3', 'Answer4', 'Answer5'];
var results = ["Answer1", "Answer1", "Answer1", "Answer1", "Answer1", "Answer2", "Answer2", "Answer2"];
console.log(getCountData(choices, results));
You can use the above function with ChartJS like this:
data: {
labels: choices,
datasets: [{
label: ': votes',
data: getCountData(choices, results),
// ...
}]
},
0👍
This fonction can count your answers based on your answers and results :
function dynamicCounter(answers,results){
return answers.map( (a) => {
var nb = 0;
results.forEach( (r) => { if(a === r)nb++ } );
return { [a] : nb }
})
}
if you want only the results to give to chartjs (as data) :
function results(answers,results){
return answers.map( (a) => {
var nb = 0;
results.forEach( (r) => { if(a === r)nb++ } );
return nb;
})
}
here a working jsfiddle
https://jsfiddle.net/wanhe6rs/1/
Source:stackexchange.com