-2

I am trying to use a variable inside of an Array, I get no Error and its not working any idea?

var hdd_usage = [12,1232113,12];
var test = JSON.stringify(hdd_usage).substr(1,JSON.stringify(hdd_usage).length-2);
console.log(test);
var chart = c3.generate({
    data: {
        columns: [
            ['data1', 1831.7,1831.7,],
            ['data2', test]
        ],
        types: {
            data1: 'area',
            data2: 'area-spline'
        }
    }
});

Tested here: http://c3js.org/samples/chart_area.html

Actually the hdd_usage is a json encoded string via php, but thats just for testing now. If you get a fix or a better solution let me know it.

Thanks.

Neoon
  • 169
  • 2
  • 12

2 Answers2

2

If you're trying to add the values of one array to another then you can try the spread operator ...

var hdd_usage = [12,1232113,12];    
var chart = c3.generate({
    data: {
        columns: [
            ['data1', 1831.7,1831.7,],
            ['data2', ...hdd_usage ]
        ],
        types: {
            data1: 'area',
            data2: 'area-spline'
        }
    }
});
Musa
  • 96,336
  • 17
  • 118
  • 137
0

In your code test would be a string and inside array it would be a single string element like "['data2',"12, 1232113, 12"]. Use Array#concat to achieve the expected result which returns a new concatenated array.

var hdd_usage = [12, 1232113, 12];
var chart = c3.generate({
  data: {
    columns: [
      ['data1', 1831.7, 1831.7, ],
      ['data2'].concat(hdd_usage)
    ],
    types: {
      data1: 'area',
      data2: 'area-spline'
    }
  }
});

See the difference in snippet :

var hdd_usage = [12, 1232113, 12];

var test = JSON.stringify(hdd_usage).substr(1,JSON.stringify(hdd_usage).length-2);
var chart = {
    data: {
        columns: [
            ['data1', 1831.7,1831.7,],
            ['data2', test]
        ],
        types: {
            data1: 'area',
            data2: 'area-spline'
        }
    }
};

var chartN = {
  data: {
    columns: [
      ['data1', 1831.7, 1831.7, ],
      ['data2'].concat(hdd_usage)
    ],
    types: {
      data1: 'area',
      data2: 'area-spline'
    }
  }
};

console.log(chart);
console.log(chartN);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188