首页 > 解决方案 > 比较和从谷歌脚本中的两个数组中获取值

问题描述

这是输入

colA = [1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3];
colB = [1.1 ,1.1 ,1.2 ,1.3, 1.3, 'ab', 2.1, 2.1, 2.2, 2.2, 'ab', 3.1, 3.2, 3.3, 3.3, 3.3, 'ab'];

我希望控制台中的输出看起来像:

1, 1.1, count of 1.1 = 2
1, 1.2, count of 1.2 = 3
1, 1.3, count of 1.3 = 2
1, AB,  count of AB  = 1
2, 2.1, count of 2.1 = 2
2, 2.2, count of 2.2 = 2
2, AB,  count of AB  = 2
.
.
.
//or something like this where I must get these three values.

代码:

for(i=0; i < colA.length; i++)
{
 for(j=0; j < colB.length; j++) 
 {
  // what to do here to compare the values.
 }
}

我是否应该使用两个 for 循环,因为我希望代码得到真正优化,因为将有大约 10k 行数据。接受任何建议。谢谢您的帮助。

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


您可以使用单个循环进行迭代,并使用 successor 和 increment 检查值count

如果不相等,则使输出和复位计数为 1。

var colA = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
    colB = [1.1, 1.1, 1.2, 1.3, 1.3, 'ab', 2.1, 2.1, 2.2, 2.2, 'ab', 3.1, 3.2, 3.3, 3.3, 3.3, 'ab'],
    count = 1,
    i,
    length = colA.length;
   
for (i = 0; i < length; i++) {
    if (colB[i] === colB[i + 1]) {
        count++;
        continue;
    }
    console.log(colA[i], colB[i], count);
    count = 1;
}


推荐阅读