Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a specific dataset from Chart.js?

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.

like image 785
Rodrigo Mota Avatar asked Jun 30 '17 19:06

Rodrigo Mota


People also ask

What is CTX in chart JS?

js convention is to call it ctx . An object literal containing the data and the configuration options that Chart. js will use to build your chart. The required properties are type and data . In our example type is 'line' because we want a line chart.

How do you delete a chart in Chartjs?

destroy() Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart. js, along with any associated event listeners attached by Chart.


1 Answers

If you're removing using data.datasets.pop(ds1) you'll never get the result you're looking for. The dataset property is an array, so let's just focus on arrays and ignore Chart.js.

First issue is that the pop() method of the Arrays type does not take an argument, so providing which element you want to remove is irrelevant. Pop() will always remove the last element from an array.

To remove a specific element from the array you need to use the splice() function.

Let's say that ds1 is the element you want to remove.

let removalIndex = data.datasets.indexOf(ds1); //Locate index of ds1
if(removalIndex >= 0) { //make sure this element exists in the array
    data.datasets.splice(removalIndex, 1);
}

This will delete the 1 record in the array starting at the index we located ds1.

like image 134
JNYRanger Avatar answered Sep 21 '22 10:09

JNYRanger