Question

I have a json-encoded array with 5000 lines all looking like the following:

[2013-01-01 07:00, 10, 50]

In order to draw a jqplot with two y-axis, I need to get two different arrays out of this one looking like the following:

array1: [2013-01-01 07:00, 10]
array2: [2013-01-01 07:00, 50]

What I tried is the following approach but it doesn't seem to work well:

var data= <?php echo json_encode($dataarray); ?>;
var array1= [];  
var array2 = [];

for(var i=0, len=data.length; i<len; i++){
  array1[i] = array1[i][0]+array1[i][1];
  array2[i] = array2[i][0]+array2[i][2];
};

Could somebody help or is there even an easier way to draw the 2-y-axis plot with my original array, without the need to split the array elements?

Was it helpful?

Solution

Assuming they are all in an array and that the items are all the same shape, you could use the following piece of code:

var data = [
  ['2013-01-01 07:00', 10, 50],
  ['2013-01-01 08:00', 20, 70]
]

var array1 = data.map(function(item){ return [item[0], item[1]]});
var array2 = data.map(function(item){ return [item[0], item[2]]});

Alternatively, you could change your original approach:

var array1 = [];  
var array2 = [];

for(var i=0, len=data.length; i<len; i++){
  array1.push([data[i][0], data[i][1]]);
  array2.push([data[i][0], data[i][2]]);
};

Finally, i think arrays are usually better to store the same kind of items. Your original data might better suited to be structured like this:

var data = [
  { date: '2013-01-01 07:00', first : 10, second: 50},
  { date: '2013-01-01 07:00', first : 20, second: 70}
]

The same solution works with only minor modifications.

OTHER TIPS

Here is O(n) time complexity approach:

var data= <?php echo json_encode($dataarray); ?>;
var array1 = [];  
var array2 = [];

var len = data.length;
for (i = 0; i < len; i++) {
    array1.push([data[i][0], data[i][1]]);
    array2.push([data[i][0], data[i][2]]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top