Kun
Kun

Reputation: 21

Highchart generate array series

I am working on a project and want to dynamically create highchart by assigning series arrays to the highchart. I use some dummy data to generate the array, however, in the example I provided below, the two columns are excatly the same which is not expected. examples

$(function () {
  var field_result = new Object();
  var series = [];
  var result_array = [];

  var fields = [32, 22]
  for (var i=0; i<fields.length; i++)
  {   
    field_result.name = fields[i];
    for (var m=0; m<4; m ++) {
      result_array[m] = Math.random()*10;
    }
    field_result.data = result_array;
    series.push(field_result);
  }


  $('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Column chart with negative values'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    credits: {
        enabled: false
    },
    series: series
  });
});

Thank you very much.

Upvotes: 1

Views: 410

Answers (1)

Martin Schneider
Martin Schneider

Reputation: 3268

You intent to create two distinct series-objects with separate data-arrays and put these in the series-array. But you are initializing these objects outside the loop for each individual series, so you end up overwriting the first data object with the second data.

You just have to move the initialization inside the loop:

$(function () {
  var series = [];    
  var fields = [32, 22];

  for (var i=0; i<fields.length; i++)
  {   
    var field_result = new Object(); // <---- moved here
    var result_array = [];           // <---- moved here

    field_result.name = fields[i];
    for (var m=0; m<4; m ++){
      result_array[m] = Math.random()*10;    
    }
    field_result.data = result_array;
    series.push(field_result);
  }
  [...]

Then in each loop iteration a new object and array will be created and filled with random data.

http://jsfiddle.net/doc_snyder/jgoyynzd/2/

Upvotes: 2

Related Questions