Encountering a problem when providing an array as a parameter to the setData

I am currently working on a project to create a dynamic Pie Chart that can switch between two different data series using a button.

Initially, I had success passing values directly to the setData() function when the button is clicked, as shown in this working demo.

However, when I tried to store my data in arrays and use them with the setData() function, I encountered an issue where the function would overwrite the first array with the second. This can be seen in this non-working demo.

In essence, directly using data values worked fine, as illustrated below:

// Button action
    $('#button').click(function () {
        var chart = $('#container').highcharts();
        bool_pie = !bool_pie;
        if(!bool_pie){
            chart.series[0].setData([129.2, 144.0, 176.0]);
        }else{
            chart.series[0].setData([29.9, 71.5, 106.4]); 
        }
    });

However, when trying to use variables (data1 and data2), the problem occurred where data1 was being overwritten by data2:

    var data1 = [29.9, 71.5, 106.4];
    var data2 = [129.2, 144.0, 176.0];
// Button action
    $('#button').click(function () {
        var chart = $('#container').highcharts();
        bool_pie = !bool_pie;
        if(!bool_pie){
            chart.series[0].setData(data2);
        }else{
            chart.series[0].setData(data1); 
        }
    });

I have been able to identify the issue, but I am currently exploring solutions to manage it effectively.

Answer №1

I have identified the issue in your code. When you pass data1 to initialize highcharts, you are actually passing a reference to the original data1 array. Highcharts converts this reference into an array of objects. To solve this, you need to pass a copy of the array so that both data1 and data2 remain as arrays:

$(function () {
    var data1 = [29.9, 71.5, 106.4];
    var data2 = [129.2, 144.0, 176.0];
    var bool_pie = true;
    $('#container').highcharts({
        chart: {
            type: 'pie'
        },
        series: [{
            data: data1.slice(0, data1.length)
        }]
    });

    // button functionality
    $('#button').click(function () {
        var chart = $('#container').highcharts();
        bool_pie = !bool_pie;
        var data = (!bool_pie) ? data2 : data1;
        chart.series[0].setData(data); // PASSING ARRAY VARIABLE
    });
});

I made changes to this line:

data: data1.slice(0, data1.length)

http://jsfiddle.net/8rjg30pc/4/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expanding just one card in React using Material UI: how can I achieve this?

I am currently working with React and Material UI to display a set of mapped cards. However, I am facing an issue where all the cards expand simultaneously when I try to expand one. I have attempted to pass an index to the "handleExpandClick" function, but ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Extracting the video identifier from YouTube's embed code

I'm currently in the process of converting a PHP preg_match expression to extract a video ID from YouTube embed code using JavaScript. Here's what I have in PHP: $pattern = '%(?:https?://)?(?:www\.)?(?:youtu\.be/| youtube\.co ...

Methods to fill a data table cell

I have recently created a table and I am facing an issue in populating the tds cells using JavaScript. The data for the table is coming from the server. Here's my table: <table id="report" class="infoRecurso" id='testExportId' style="wid ...

Tips for testing components with React JS using jest and enzyme

Attempting to perform a unit test on the code snippet below: handleChange = (e) => { let localState = Object.assign({}, this.state) localState[e.target.name] = e.target.value this.setState(localState) this.props.addMetaInformation(localState) } } I&a ...

The combination of Import() and import * does not function properly when used together, particularly in Node.js

Currently, I am developing an application with the following setup: babel-node -> Express server -> Webpack middleware -> React My main goal is to incorporate code-splitting using import(). Here is a snippet from my .babelrc file: { "presets ...

Element UI: Triggering an event when the sort caret is clicked

Is it possible to trigger an event when the sorting carets are clicked on a table with sortable columns, ideally with the same parameters as the header-click event? I am able to emit an event by clicking on the header of any sortable column (header-click) ...

Unusual situation observed in ExpressJS: Callback function fails to execute

Currently, I am facing an issue with my web app built using expressjs and node. It seems that the functionality is not working correctly. An unusual situation has occurred where accessing the first link in the browser yields the expected results, while th ...

Issue with Dropzone not functioning correctly within Vue transition modal

I've implemented a dropzone function in the mounted function, which works perfectly when the dropzone is outside of a modal in the view. However, when I try to use it within a modal with a transition effect, it doesn't work. Any suggestions on ho ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

What is the best 'event' to pair with an <input/> element in iOS/Android development?

Looking for a way to toggle results when a user starts typing in a search field? Here are some event options: mousedown / mouseup touchstart / touchend focus You could also consider using the "change" event instead of "click" to check for text input an ...

JQuery's find() method followed by length/size() is resulting in a return

I'm running into an issue with dynamically created divs. Here's how they are created: // Loop through and append divs to #result_main_search $("#result_main_search").append('<div class="singleresult_main_search"> <a href="http:// ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

Learning to monitor for incoming messages in a Discord channel from the ground up

I am eager to understand how to detect new messages exclusively using requests made to the Discord API. While I have mastered loading messages by fetching , I am struggling to grasp how to listen for incoming messages. It appears that this feature is not ...

What factors can impact the speed at which an array operates within a program?

I've encountered an unusual issue on two similar machines, both running ubuntu 10.04 amd64. Below is the code in question: <?php $array = array('a', 'b'); for($i = 0; $i < 400000; $i++) { is_array($array); } This code ...

Unable to place within div

Utilizing HTML5 to implement the "DnD" function. There is a button that adds divs. I want to be able to drag items into these newly added divs. Currently, I can only drag into existing divs and not the ones added later. How can I resolve this issue ...

Filter search results using selected region from dropdown menu

I have been attempting to retrieve the value from a dropdown list and customize the search functionality specifically for the selected field. The client should only be able to search within the chosen zone in the dropdown. I have been searching for a solut ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

I want to create a feature on my website where users can generate a random password by clicking a button on the password field. This will

After setting up a form in HTML that connects to a function in views.py within the Django framework, I decided to enhance it by adding a button that automatically populates the password field with a randomly generated password. To achieve this, I utilized ...

What is the best way to check and verify Array inputs in Laravel version 5.0?

In my table, users are able to input information and have the option to add or remove rows. To achieve this functionality, I implemented a cloning function. The structure of my HTML is as follows: <input type="text" class="form-control" name="TB1_a[]" ...