0

I'm trying to place a data into a specific location in an array using array.splice(). So that I can get data from sheet1 to the main sheet in the right column.

Here's how it looks so far.
(The Code actually returns correctly at Logger.log)

var header1 = data1[0]; //Header of Sheet1
var header2 = data2[0]; //Header of sheet2
var newData = new Array(44); //There are 45 columns

for (i in data1) {
  if (i > 0) { //Take Row by Row Except Header of Sheet1
  var row = data1[i];
  if (row != "") {

    for (j in data2) { //Searching Through All Rows of Sheet2
      var row2 = data2[j];
      if (row[0] == row2[4]) { //If Data In Column Match That Row, Proceed
        //Getting the Right Index of SameName Column
        for (i in header2) {
          var col = header2[i];
          for (j in header1) {
            var col2 = header1[j];
            if (col == col2) {
              Logger.log(j+" "+row2[i]);
              newData.splice(j,0,row2[i]);
            }
          }
        }
      }
    }
  }
}

It Returns Correctly 1 Line before:

Logger.log(j+" "+row2[i]); 42 Timestamp
3 Name
4 lastName
2 DoB
0 ID
.
.
.
1 Type
//All data returns correctly with the correct index (and none is null)

Here's The Issue:

Logger.log(newData);
[ID, Type, null, null, DoB, null, ...., TimeStamp, null, null]
DoB had index at 2 in previous line at Logger.log, but somehow the array has null at pos2. Also... newData.length increases from 44 to 68

Somehow the index and data got mixed up later in the array.
Thank you in advance to all of you.

1 Answers1

0

If you log your newly-instantiated array, you will see that, by default, all array elements are assigned a value of 'null'. In JavaScript, arrays are dynamic, which means their size is not pre-determined.

Assuming that for some rows the condition 'if (row[0] == row2[4])' evaluates to 'false', some indices will be skipped. Naturally, it will produce null elements in your fixed-size array.

Use array literal notation and Array.prototype.push() method to add new elements:

var newData = [];
newData.push(element);

Also, you shouldn't be using the 'for in' loop for iterating over arrays. Using it is precisely why you don't see 'null' values being logged. More details here Why is using "for...in" with array iteration a bad idea?

Anton Dementiev
  • 5,451
  • 4
  • 20
  • 32