• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

175
Views
Why is this for loop logging correctly, but write to sheet wrongly using GAS?

I'm running this for loop and modifying some values on the go. It logs the values changed correctly in each iteration, but it repeats the last iteration when writing to sheets.

const rngList = cadSheet.getRangeList(dataRng).getRanges();

  //Gets the ranges' values and push them into an array;
  let values = [];
  for (let i = 0; i < rngList.length; i++) {
    values = [].concat(values, rngList[i].getValues().flat());
    //values.push([rngList[i].getValue()]);
  }

  let itens = [];
  for (let a = 0; a < tamanhosEscArr.length; a++) {
    for (let r = 0; r < coresEscArr.length; r++) {
      values[4] = variacao++;//Increments an ID number
      values.splice(29, 1); //removes this element
      values.splice(29, 0, tamanhosEscArr[a]); //inserts size being iterated over

      values.splice(30, 1);//removes this element
      values.splice(30, 0, coresEscArr[r]); //inserts color being iterated over

      Logger.log('Item: ' + values) //logs all 18 or so items, with their corresponding sizes and colors
      itens.push(values);
    }
  }
  suporteSheet.getRange(suporteSheet.getLastRow() + 1, 1, itens.length, itens[0].length).setValues(itens); //Writes the last iteration as many times as the iterations (18)

This is the log, showing the correct result: enter image description here

This is how this is writing to the spreadsheet: enter image description here

I can't see where the flaw is here, besides my existence.

Thanks for the light!

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try to change:

itens.push(values);

to:

itens.push(values.slice());

Еxplanation

Log shows you the current state of the array values at every iteration of the loop. During the next iteration, you change the array values. And all 'previous instances' of the array are changing as well. This is why you're getting the 18 identical arrays. Because all of them are 'references' to the same array values.

If you want to prevent the changes in the 'previous instances' you have to make a copy of current state of the array values and put in the itens this copy. The method array.slice() returns a copy of a given array.

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error