简体   繁体   中英

Comparing & getting values from two arrays in google script

Here is the input ,

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'];
  • Both the arrays have the same length.
  • if there are total 6 '1's in colA then there will be only 6 of the 1s item(1._) in colB.

I want the output in the console to look like:

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.

Code:

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

Should I go with two for loops because I want the code to be really optimized as there is going to be around 10k rows of data. Open to any suggestions. Thanks for the help.

You could iterate with a single loop and check the value with the successor and increment count .

If unequal make the output and reset count to one.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM