Reputation: 2372
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:
This is how this is writing to the spreadsheet:
I can't see where the flaw is here, besides my existence.
Thanks for the light!
Upvotes: 1
Views: 52
Reputation: 14537
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.
Upvotes: 2