Reputation: 3
I'm a begginer ok... I'm trying to use math operators in array elements, but I don't know what I'm doing wrong. I used the parseInt and Number function to increment array elements with some integers, but it's not working.
The original values from my sheet are: [[1000.0], [1000.0], [3000.0], [1000.0], [], [], [], [], [], []]
When I tryed without parseInt/Number the result was: [01000100030001000, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
When I tryed with parseInt/Number: [NaN, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
function myFunction() {
var ssCDB = SpreadsheetApp.getActive().getSheetByName("CDB");
var cdbRange = ssCDB.getRange(3, 3, 10, 1).getValues();
var cdbSum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
Logger.log(cdbRange);
for (var i=0; i<cdbRange.length; i++) {
cdbSum[0] = cdbSum[0] + cdbRange[i];
//cdbSum[0] = parseInt(cdbSum[0]) + parseInt(cdbRange[i]);
}
Logger.log(cdbSum);
}
I'm expecting something like: [6000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
what am I doing wrong? Any ideas?
Upvotes: 0
Views: 3264
Reputation: 64042
I think this is what you're trying to do:
function myFunction() {
var sh=SpreadsheetApp.getActiveSheet();
var vA=sh.getRange(3,3,10,1).getValues();
var sumA=[0,0,0,0,0,0,0,0,0,0];
for(var i=0;i<vA.length;i++) {
sumA[i]+=vA[i][0];//a 1 column 2d array
}
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(sumA.join(', ')), 'Sum');//Do not need this it just show your sum values
}
Upvotes: 0
Reputation: 201348
How about this modification? I think that there are 3 issues for your situation.
cdbRange
is 2 dimensional array. But you are using it like cdbRange[i]
.
cdbRange[0]
is [1000.0]
which is an object.cdbSum[0] = cdbSum[0] + cdbRange[i]
, cdbSum[0]
is used as a string value. Because cdbRange[i]
is an object. When it adds an object to a number, it becomes the string type.
01000100030001000
. The initial value of cdbSum[0]
is 0
.cdbRange
is undefined
.
NaN
.In order to avoid these issues, please modify as follows.
cdbSum[0] = cdbSum[0] + cdbRange[i];
if (cdbRange[i][0]) cdbSum[0] += cdbRange[i][0];
or
if (cdbRange[i][0]) cdbSum[0] += Number(cdbRange[i][0]);
[6000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
cdbRange
to cdbSum[0]
.If I misunderstood your question, please tell me. I would like to modify it.
Upvotes: 1