javascript - 比较和从谷歌脚本中的两个数组中获取值
问题描述
这是输入,
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'];
- 两个数组的长度相同。
- 如果 colA 中总共有 6 个“1”,那么 colB 中将只有 6 个 1 项目(1._)。
我希望控制台中的输出看起来像:
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 行数据。接受任何建议。谢谢您的帮助。
解决方案
您可以使用单个循环进行迭代,并使用 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;
}
推荐阅读
- java - 在停止和重新启动我的应用程序时,我收到一个地址已在使用中的 JMX 错误
- java - 约束布局在不同设备上执行不同
- python - Python Requests 库不需要的 GET 请求冒号转义
- reactjs - 与 Expo 相机相关的 Expo 常量包错误,与 SDK 34 相关
- php - PHP 在执行 tesseract 后停止脚本
- angular - 使用 Angular Web 客户端从移动设备发出 http 请求
- c# - 如何解析 android 中的 KSOAP 端点,保持用于登录的同一会话,然后在同一 Web 会话中请求其他端点?
- regex - 匹配正则表达式中的单词中间或整个单词
- jsf - Netbeans 不会自动完成嵌套 var 的属性
- javascript - 如何从 javascript 在 firestore 文档中填充时间戳类型的值?