Reputation: 191
Hi Helpful Contributors,
I have a loop that supposed to do below:
I'm stuck on step 4. Below is my code:-
const itemsheet=SpreadsheetApp.openById("1c0-vzYQA_9KVHuSYiKHG-3iBBGhTg3EcCZBm7rZDIpM").getSheetByName('item');
const datasheet=SpreadsheetApp.openById("1c0-vzYQA_9KVHuSYiKHG-3iBBGhTg3EcCZBm7rZDIpM").getSheetByName('data');
function weightcalculator() {
const lrow=datasheet.getLastRow();
const lastrow=itemsheet.getLastRow();
for(var i=13;i<13+(lrow-1);i++){
const qtyheader=itemsheet.getRange(1,i).getValue();
const qty=itemsheet.getRange(lastrow,i).getValue();
const item=getItem(qtyheader); //
const data=datasheet.getDataRange().getValues();
const itemrow=data.findIndex(itemID=> {return itemID[2] == item}) +1;
const weightval=datasheet.getRange(itemrow,7).getValue();
const weight=weightval*qty;
}
}
I don't know how to keep each total weight after each looping and then sumup all. Below screenshot is the main gsheet "item" with qty value in each column.
Below is screenshot of another gsheet "data" which being referred to get the unit weight.
Upvotes: 0
Views: 55
Reputation: 27348
You can push every weight into a weight
array and then sum up the elements of this array.
Here is one way to calculate the total weight:
const ss = SpreadsheetApp.openById("1c0-vzYQA_9KVHuSYiKHG-3iBBGhTg3EcCZBm7rZDIpM")
const itemsheet=ss.getSheetByName('item');
const datasheet=ss.getSheetByName('data');
function weightcalculator() {
const lrow=datasheet.getLastRow();
const lastrow=itemsheet.getLastRow();
const weight = [];
for(var i=13;i<13+(lrow-1);i++){
const qtyheader=itemsheet.getRange(1,i).getValue();
const qty=itemsheet.getRange(lastrow,i).getValue();
const item=getItem(qtyheader); //
const data=datasheet.getDataRange().getValues();
const itemrow=data.findIndex(itemID=> {return itemID[2] == item}) +1;
const weightval=datasheet.getRange(itemrow,7).getValue();
weight.push(weightval*qty);
}
const total_weight = weight.reduce((a, b) => a + b, 0);
}
Upvotes: 1