jlbriggs
jlbriggs

Reputation: 17800

Highcharts - series.remove(); 4 series in chart, only 2 removed

Live example:

I have a set up where I have a chart with four series. I want to allow the user to select a different data set, and then

  1. remove the existing series
  2. add the new series

I am stuck at the 'remove' phase, however, because after the first two series are removed, it tells me the next 2 are undefined.

The function to remove the series:

function updateData(chart, dataSet) {
    console.log(chart);
    $.each(chart.series, function(i,ser) {
        if(typeof(ser) != 'undefined') {
            console.log(ser);
            ser.remove();
        }
    });
}

Which leaves 2 series still on the chart.

When I console.log the chart object, it only lists two series.

The questions:

  1. Am I doing this wrong? Is there a better way to remove all of the series?
  2. Why does the chart only show two series instead of four?

Upvotes: 0

Views: 975

Answers (1)

Jugal Thakkar
Jugal Thakkar

Reputation: 13482

Looks like your code is modifying the array that is being iterated over. Try this and observe the logs.

$.each(chart.series, function(i,ser) {        
        console.log(i + " / " + chart.series.length);
        ser.remove();        
});

Observe how the current index i is increasing and your series length is decreasing after each iteration.

0 / 4
1 / 3
2 / 2 << chart.series[2] becomes undefined for chart.series.length=2

At the third iteration, i=2 & chart.series.length=2 => ser=undefined

Proper way to remove all series data from a highcharts chart? provides the right way of doing this. Always remove the series at index 0 if it exists.

while(chart.series.length > 0)
    chart.series[0].remove(true);

Upvotes: 2

Related Questions