0

EDIT: My problem was that earlier in the code I had:

var summedImpsByWeekTable = impsByWeekTable

This was not cloning the object but instead was just copying a reference to the same object. Instead, use

var impsByWeekTable = JSON.parse(JSON.stringify(budgetTable));

Leaving the rest of the question below in its originality to hopefully help anyone like me that didn't know how else to ask this question.


Either I have gone insane or Google Script is seriously bugged. (I suspect it's the former.) (Please bear with me, I have extremely little professional training and am mostly learning on the fly.)

My code wasn't working as it should and so I simplified it down as much as I could to demonstrate the problem. This for loop is modifying impsByWeekTable and it shouldn't. What I want the code to accomplish is for every value of a table to equal the sum of all preceding values in that row. So I want [5,5,6,6] to transform into [5,10,16,24]. Here is my code:

Logger.log(impsByWeekTable)
    x = 1;
    for (y = 2; y <= numOfWeeks-2; y++) {
      for (z = 1; z <= y-2; z++) {
      summedImpsByWeekTable[x][y] = impsByWeekTable[x][y-z] + summedImpsByWeekTable[x][y];
      }
    }
 Logger.log(impsByWeekTable)

The problem is that the for loop is somehow modifying impsByWeekTable. The Logger spits out this the first time for impsByWeekTable

[CTV, 55.0, 90909.09090909091, 109090.90909090909, 109090.90909090909, 72727.27272727274, 0.0]

and this the second time for impsByWeekTable

[CTV, 55.0, 90909.09090909091, 200000.0, 400000.0, 763636.3636363636, 1454545.4545454546]

This is wrong, right? There's nothing in the for loop that should modify impsByWeekTable. I've tested it as many ways as I can think to and can't figure it out. Help?

  • Some (or all) of the values inside `summedImpsByWeekTable` must be referring directly to value(s) inside `impsByWeekTable`. You probably need to clone the object properly to not affect the original. – CertainPerformance Jun 21 '22 at 20:43
  • Thank you! TIL objects aren't cloned with just "=". For anyone coming after me, I used var summedImpsByWeek = JSON.parse(JSON.stringify(impsByWeekTable)); in this situation. – Chris Verrill Jun 21 '22 at 20:50
  • Are you saying you used `obj2 = obj1`, or are you saying you used `obj2 = JSON.parse(JSON.stringify(obj1))` and you are still getting changed results in `obj1`? – TheWizEd Jun 21 '22 at 20:58
  • I used obj2 = obj1. I'll update the question accordingly – Chris Verrill Jun 21 '22 at 20:59

0 Answers0