'Variable value is not getting updated after adding an element to the array in apps script(Google Sheets)
This is part of the code.
var newarray = [
["A","B"],
["C","D"]
];
var dimensions = newarray.length;
ss.getRange(15,8).setValue(dimensions);
newarray.push(["Bharat","Lata"])
ss.getRange(18,8).setValue(newarray.length);
ss.getRange(21,8).setValue(dimensions);
Numbers in 15th, 18th, 21st row
I was expecting that dimensions value will be equal to 3 after adding an element to the newarray.
Solution 1:[1]
This is happening because you're not updating the variable dimensions after pushing new row in newarray.
Try following modification:
var newarray = [["A","B"],["C","D"]];
var dimensions = newarray.length;
ss.getRange(15,8).setValue(dimensions);
newarray.push(["Bharat","Lata"])
dimensions = newarray.length;
ss.getRange(18,8).setValue(newarray.length); // you can use dimensions here too
ss.getRange(21,8).setValue(dimensions);
Solution 2:[2]
You have to update also var dimensions = newarray.length; after updating newarray
function myFunction() {
var sh = SpreadsheetApp.getActiveSheet()
var newarray = [
["A", "B"],
["C", "D"]
];
var dimensions = newarray.length;
sh.getRange(15, 8).setValue(dimensions);
newarray.push(["Bharat", "Lata"])
dimensions = newarray.length;
sh.getRange(18, 8).setValue(newarray.length);
sh.getRange(21, 8).setValue(dimensions);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vector |
| Solution 2 | Mike Steelson |
