[英]Sum arrays if a condition is met within a loop
I am using the code below to create a table.我正在使用下面的代码来创建一个表。 It works fine.
它工作正常。
My final goal is to add a sub-total for "de-prioritized".我的最终目标是为“取消优先级”添加小计。 Since I am already looping the table, I wanted to leverage the existing loop.
因为我已经在循环表格,所以我想利用现有的循环。 (without looping every value in the array which I am afraid will slow down the code)
(不循环数组中的每个值,恐怕会减慢代码速度)
For Example If my table is:例如如果我的表是:
[A,de-prioritized,2,1,0,0,1],
[B,de-prioritized,0,2,1,1,0],
[C,other,0,5,2,1,1]
I want to get: [2,3,1,1,1] (as sum of [2,1,0,0,1]+[0,2,1,1,0]).我想得到:[2,3,1,1,1](作为 [2,1,0,0,1]+[0,2,1,1,0] 的总和)。
In other words: Let's say I have a table A1:F10.换句话说:假设我有一张桌子 A1:F10。 In A there is a flag (either "de-prioritized" or not), while in B1:F10 there are values.
在 A 中有一个标志(无论是否“取消优先级”),而在 B1:F10 中有值。 I want to replicate the formula in each column: SUMIF(A1:A10,"de-prioritized",B1:B10),SUMIF(A1:A10,"de-prioritized",C1:C10),SUMIF(A1:A10,"de-prioritized",D1:D10) and so on.
我想在每一列中复制公式: SUMIF(A1:A10,"de-prioritized",B1:B10),SUMIF(A1:A10,"de-prioritized",C1:C10),SUMIF(A1:A10, “去优先级”,D1:D10)等等。 I cannot set the formulas because the range in the example above is dynamic.
我无法设置公式,因为上面示例中的范围是动态的。 I tried to set the formulaR1C1 with sumif in the script, but it did not work.
我尝试在脚本中使用 sumif 设置公式 R1C1,但它不起作用。
I found a similar problem, but I may have n arrays to sum and I am not able to fit the solution in mine: Javascript - Sum two arrays in single iteration我发现了一个类似的问题,但我可能有 n arrays 求和,我无法在我的解决方案中拟合: Javascript - 在单次迭代中求和两个 arrays
Existing code I have:我现有的代码:
var l = sheet2.getRange('A1').getValue();
for (var i = 0; i<l ;i++) {
if (sheet3.getRange(i+3,2).getValue() == 'de-prioritized') {
sheet3.getRange(i+3,1,1,sheet3.getLastColumn()).setBackgroundRGB(250, 240, 230);
} else sheet3.getRange(i+3,1,1,sheet3.getLastColumn()).setBackgroundRGB(225, 247, 232)
}
[2,3,1,1,1]
from [["A","de-prioritized",2,1,0,0,1],["B","de-prioritized",0,2,1,1,0],["C","other",0,5,2,1,1]]
using Google Apps Script.[2,3,1,1,1]
[["A","de-prioritized",2,1,0,0,1],["B","de-prioritized",0,2,1,1,0],["C","other",0,5,2,1,1]]
使用 Google Apps 脚本。const arr = [["A","de-prioritized",2,1,0,0,1],["B","de-prioritized",0,2,1,1,0],["C","other",0,5,2,1,1]];
const res = arr.reduce((ar, [,b,...cdefg]) => {
if (b == "de-prioritized") ar = ar.length > 0 ? ar.map((e, i) => e + cdefg[i]) : cdefg;
return ar;
}, []);
console.log(res) // <--- [2,3,1,1,1]
const arr = [["A","de-prioritized",2,1,0,0,1],["B","de-prioritized",0,2,1,1,0],["C","other",0,5,2,1,1]]; const res = arr.reduce((ar, [,b,...cdefg]) => { if (b == "de-prioritized") ar = ar.length > 0? ar.map((e, i) => e + cdefg[i]): cdefg; return ar; }, []); console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.