How to delete a specific dataset from Chart.js?

Viewed 15628

I want to add & delete datasets from chart.js using checkboxes.

Right now I am adding using this:

var ds1 = {
    label: ..
    data: .. etc
};
data.datasets.push(ds1);

When I uncheck any of the checkboxes, it's always deleting the last dataset added, which is not necessary the one of the checkbox.

I'm using data.datasets.pop(ds1); to remove the when a checkbox is clicked.

4 Answers

If you look at ChartJS' internal object chart.data.datasets, the datasets are distinguishable by the label you gave when initially adding the datasets (it's weird that there's no ID):

enter image description here

So it's really just a matter of filtering out an object from the array by that Label, and calling chart.update();.

// Filter out and set back into chart.data.datasets
chart.data.datasets = chart.data.datasets.filter(function(obj) {
    return (obj.label != targetLabel); 
});
// Repaint
chart.update();

Actually you can add an ID in your dataset :

var ds1 = {
    label: ..
    data: ..
    id : 'myId'
};
data.datasets.push(ds1);

It will not affect your dataset or your chart in anyway

Then you can find and delete (or update) :

data.datasets.find((dataset, index) => {
    if (dataset.id === 'myId') {
       data.datasets.splice(index, 1);
       return true; // stop searching
    }
});
myChart.update();
Related