-1

Here's my relevant code:

var data_final = [];
      for(var i = 1; i<4; i++) {
        $.ajax({
          ...
          },
          crossDomain: true,
          success: function(raw_data) {

            // Put the data in the proper array
            for(var d in raw_data.data) {
              data_final[i-1].push([parseDate(d), raw_data.data[d]]);
            }
            data_final[i-1] = twoDimensionalSort(data_final[i-1]);
          }
        });

I get an error on this line: data_final[i-1].push([parseDate(d), raw_data.data[d]]); that "Uncaught TypeError: Cannot read property 'push' of undefined".

Does the .push method not allow one to push an array into an array? It works fine if I take out the [i-1] specification in data_final, but I need that to specify where the data should be pushed.

sir_thursday
  • 5,270
  • 12
  • 64
  • 118

5 Answers5

5

You have an array

var data_final = [];

this array is now empty, so doing

data_final[i-1]

gets you nothing, it's undefined, and

data_final[i-1].push(something);

doesn't work, as you can't push to undefined
you should probably just do

var arr = [];

for(var d in raw_data.data) {
    arr.push([parseDate(d), raw_data.data[d]]);
}

data_final.push(arr);
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

Just try with:

var data_final = [];
for(var i = 1; i<4; i++) {
    if (data_final[i-1] == undefined) data_final[i-1] = [];
    ....
hsz
  • 148,279
  • 62
  • 259
  • 315
0
var data_final = []

You are defining an array. You are getting a value that is not an array by indexing it.

The only way this could work is if data_final is a multi-dimensional array:

var data_final = [ [], [], [] ];
data_final[0].push([1,2,3]);
Sam P
  • 1,821
  • 13
  • 26
0

Actually you can push something into data_final[]:

       data_final.push("test");
       data_final.push(["pushing","an","array"]);

But you cannot actually push anything into an undefined element of the data_final array:

       //this will raise an error!!
       data_final[5].push("test");

So first you have to initialize each undefined element:

       data_final[5] = [];
       data_final[5].push("Now the 5th element is a well defined array");
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
-1

push only appends data to the end of the array, if you would like to put data in a specific place in the array, i recommend that you use splice

view this mdn documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Hawk
  • 788
  • 1
  • 6
  • 18