Rodrigo Mota Rodrigo Mota - 5 months ago 38
Javascript Question

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.

Answer Source

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.