Reputation:
I can't seem to solve this problem: my label sends me back lists, I would like in my case here to have only HOME40, HOME60 and PRO as label, but unfortunately it returns the concatenation of that, I would also like to change color, if the product is HOME40 then the color must be green, if PRO then red. anyone have any suggestions?
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<div class="trendmensuel">
<canvas id="trendmensuel"></canvas>
</div>
<script>
var trendMensuel = [
{ produit: "HOME40Z", mois: "Janvier", effectif: 6, bgColor: "red" },
{ produit: "HOME60", mois: "Janvier", effectif: 7, bgColor: "green" },
{ produit: "HOME40Z", mois: "Février", effectif: 6, bgColor: "red" },
{ produit: "PRO", mois: "Fevrier", effectif: 9, bgColor: "blue" },
{ produit: "HOME60", mois: "Mars", effectif: 3, bgColor: "green" },
];
var label_trendMensuel = trendMensuel.map(function(e){
return e.mois;
});
var produit_trendMensuel = trendMensuel.map(function(e){
return e.produit;
});
var effectif_trendMensuel = trendMensuel.map(function(e){
return e.effectif;
});;
var ctx = document.getElementById("trendmensuel");
var chart = new Chart(ctx, {
type :"bar",
data : {
labels : label_trendMensuel, // ito efa mety
datasets:[
{
type: "bar",
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1,
label: produit_trendMensuel,
data: effectif_trendMensuel,
},],
},
});
</script>
Upvotes: 1
Views: 668
Reputation: 5937
Is this what you want?
var trendMensuel = [
{ produit: "HOME40Z", mois: "Janvier", effectif: 6, bgColor: "red" },
{ produit: "HOME60", mois: "Janvier", effectif: 7, bgColor: "green" },
{ produit: "PRO", mois: "Janvier", effectif: 9, bgColor: "blue" },
{ produit: "HOME40Z", mois: "Février", effectif: 3, bgColor: "red" },
{ produit: "HOME60", mois: "Février", effectif: 4, bgColor: "green" },
{ produit: "PRO", mois: "Février", effectif: 1, bgColor: "blue" },
];
const data = trendMensuel.reduce(
(a, b) => {
const i = a.months.findIndex(x => x === b.mois);
const j = a.products.findIndex(y => y.label === b.produit);
if (i === -1) {
a.months.push(b.mois);
}
if (j === -1) {
a.products.push({
type: "bar",
backgroundColor: b.bgColor,
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1,
label: b.produit,
data: [b.effectif],
});
} else {
a.products[j].data.push(b.effectif);
}
return a;
},
{ months: [], products: [] }
);
var ctx = document.getElementById("trendmensuel").getContext("2d");
var chart = new Chart(ctx, {
type: "bar",
data: {
labels: data.months, // ito efa mety
datasets: data.products,
},
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="trendmensuel" width="400" height="400"></canvas>
Upvotes: 1