I try to create formula inside array after filter this array, my array sometime don't give me price and sometime don't give me total price: I need if the Price in array has 0.0 I want to change this to TotalPrice/Qty like first array 600/20=30 , The price is 30. and in second array This is my code : TotalPrice is 0.0 do QtyPrice=TotalPrice : 1020=200 , thee TotalPrice is 200 .
I need output like that:
[{Qty:20, Price:30, TotalPrice:600}, {Qty:10, Price:20, TotalPrice:200},
{Qty:5, Price:100, TotalPrice:500}]
And then I put it to sheet by this code:
sh.getRange(5,5,oA.length, oA[0].length).setValues(oA);
Thanks.
function arrayFormula() {
const data = '[{"Qty":"20", "Price":"0.0", "TotalPrice":"600"}, {"Qty":"10", "Price":"20",
"TotalPrice":"0.0"}, {"Qty":"5", "Price":"100", "TotalPrice":"500"}]';
Logger.log("Array: "+ data);
const obj = JSON.parse(data);
const ss = SpreadsheetApp.getActive();
const oA = obj.map(obj => [obj.Qty, obj.Price,obj.TotalPrice]);
// put array return to sheet
//sh.getRange(5,5,oA.length, oA[0].length).setValues(oA);
var filtered = oA.filter(function (el) {
if (el[1]!=0) {
return obj.Total/obj.Qty;
} else {
return false
}
});
console.log("Array After Filter: " + filtered);
}
Return me :
1:16:27 PM Info Array: [{"Qty":"20", "Price":"0.0", "Total":"600"}, {"Qty":"10",
"Price":"20", "Total":"0.0"}, {"Qty":"5", "Price":"100",
"Total":"500"}]
1:16:27 PM Info Array After Filter:
Like this photo: enter image description here
Probably something like this:
function main() {
const data = `[
{"Qty":"20", "Price":"0.0", "TotalPrice":"600"},
{"Qty":"10", "Price":"20", "TotalPrice":"0.0"},
{"Qty":"5", "Price":"100", "TotalPrice":"500"}
]`;
const obj = JSON.parse(data);
const calc_price = obj =>
obj.Price == 0 ? obj.TotalPrice / obj.Qty : obj.Price;
const calc_total_price = obj =>
obj.TotalPrice == 0 ? obj.Price * obj.Qty : obj.TotalPrice;
const oA = obj.map(o => [o.Qty, calc_price(o), calc_total_price(o)]);
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
sh.getRange(5,5,oA.length,oA[0].length).setValues(oA);
}
Output: