Not able to set dataset value in chart.js

👍:0

my problem is that after the loop finishes when i am checking the
value of datasetValue[0].data i am getting the same value which sholud
be of datasetValue[1].data

Your issue is that you are setting the data of both chart datasets to the same array object (distdata). When you update the array, both dataset’s data object change (because they 2 variables that point to the same object)

You can fix this easily by creating a copy of distdata when you assign it to the data property of the dataset. The easiest way to do this is using slice() (see Javascript fastest way to duplicate an Array – slice vs for loop for a more ways to do this).

In short, change your dataset assignment to be like so (notice the extra .slice())

...
if (i == 0) {
    datasetValue[0] =
    {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.5)",
        strokeColor: "rgba(151,187,205,0.8)",
        highlightFill: "rgba(151,187,205,0.75)",
        highlightStroke: "rgba(151,187,205,1)",
        data: distdata.slice()
    };
}
if (i == 1) {
    datasetValue[1] =
    {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.5)",
        strokeColor: "rgba(151,187,205,0.8)",
        highlightFill: "rgba(151,187,205,0.75)",
        highlightStroke: "rgba(151,187,205,1)",
        data: distdata.slice()
    };
}
...

Leave a comment