wookieebreath
wookieebreath

Reputation: 67

Google Apps Scripts setValues() incorrect height error

I've looked at some other questions similar to this, but I'm getting my array in a unique way and I can't figure out for the life of my how to change it to a 2D array.

  //Special function for adding arrays, just use sumArray on first array with second array in parenthesis
  //==========================================
  Array.prototype.sumArray = function (arr) {
    
    var sum = this.map(function (num, idx) {
      return num + arr[idx];
    });
    
    return sum;
  }
  var array1 = [1,2,3,4];
  var array2 = [5,6,7,8];
  var sum = array1.sumArray(array2);
  Logger.log("sum: " + sum);
  //==========================================

  var calc = ss.getRangeByName( "calc" );
  var target = ss.getRangeByName( "target" );
  var current = ss.getRangeByName( "current" );
  var left = ss.getRangeByName( "left" );
  
  var gainedEVs = calc.getValues();
  var goalEVs = target.getValues();
  var oldEVs = current.getValues();
  var leftEVs = left.getValues();
  
  //Make everything ints
  //==========================================
  for(var i = 0; i < oldEVs.length; i++) {
    Logger.log(oldEVs.length);
    oldEVs[i] = parseInt(oldEVs[i]);
  }
  for(var i = 0; i < gainedEVs.length; i++) {
    
    gainedEVs[i] = parseInt(gainedEVs[i]);
  }
  for(var i = 0; i < goalEVs.length; i++) {
    
    goalEVs[i] = parseInt(goalEVs[i]);
  }
  for(var i = 0; i < leftEVs.length; i++) {
    
    leftEVs[i] = parseInt(leftEVs[i]);
  }
  //==========================================
  
  var newEVs = [[oldEVs.sumArray(gainedEVs)]];
  var newLeft = [[goalEVs.subArray(newEVs)]];

  //Now I try to set values and I get the error
  current.setValues(newEVs);

I've tried changing the setValues to setValues([newEVs]); but that doesn't work either. Any clue on how I can get my array of newEVs to be the correct height? It has the right number of values, but those values are being stored in columns, not rows. (in this case all of my ranges are 6 rows 1 col)

Upvotes: 1

Views: 106

Answers (1)

Tiffany G. Wilson
Tiffany G. Wilson

Reputation: 573

Since your ranges are small, you don't have to worry too much about performance, so you can convert them from rows to columns using a loop:

var column = [];
for (var i=0; i<newEVs.length; i++){
  column.push([newEVs[i]]);
}
current.setValues(column);

Upvotes: 2

Related Questions