Search code examples
javascriptdygraphs

Javascript multiple array push() differences


I have problem with pushing data. I want to prepare data (time,temperature,humidity) for plotting (Dygraphs). But when I´m filling variable data with this one code (see below) I don´t get graph.

for (var i = 0; i < time.length; i++){
  var t = new Date (time[i]);
  data.push(t);
  for(var n = 0; n < 2; n++){
    data.push([data_graph[n][i]]);
  }
}

But when I leave one for-cycle and manually write nums of arrays (see below), It works and I get graph.

for (var i = 0; i < time.length; i++){
  var t = new Date (time[i]);
  data.push([t,data_graph[0][i],data_graph[1][i]]);
}

I got idea to use temporary variable, but also with no success.

 for (var i = 0; i < time.length; i++){
   var data_temporary = [];
   var t = new Date (time[i]);
   for(var n = 0; n < 2; n++){
     data_temporary.push([data_graph[n][i]]);
   }
   data.push([t,data_temporary]);
 }

So my question is...where could be a problem? Thanks in advance for answers.


Solution

  • Yes, your three code snippets generate three different data structures:

    1. [t, [datagraph…], [datagraph…], t, [datagraph…], [datagraph…], …]
    2. [[t, datagraph…, datagraph…], [t, datagraph…, datagraph…], …]
    3. [[t, [[datagraph…], [datagraph…]]], [t, [[datagraph…], [datagraph…]]], …]

    Too often you pushed one-element-arrays, btw.

    So if you want struc#2 generated by a loop, use

    for (var i=0; i<time.length; i++) {
        var t = new Date (time[i]);
        var temp = [t]; // or temp=[]; temp.push(t);
        for (var j=0; j<data_graph.length; j++) // or j<2 if that's certain
            temp.push(data_graph[j][i]);
        data.push(temp);
    }