Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest method to compare two arrays for find equal value on Google app script

I have two arrays as below.

bulkSheet[] - Original array
resultsArray[] -  Checking array

I am comparing first element of 'bulkSheet' array with 'resultArray'. Below code is what I have done so far. It executes fine but take long time and gives Exceeded maximum execution time error.

for(var line in bulkSheet) {
  for (var line2 in resultsArray)
  {
    if(bulkSheet[line][0] == resultsArray[line2][0])
    {
      // matched items
    }
  }
}

Is there any fastest way?

like image 704
iJay Avatar asked Sep 05 '25 23:09

iJay


1 Answers

Thank you @sandy-good !, If it is an 1D array we can use indexOf() method.

for(var line in firstArray) 
{
 var isMatched = secondArray.indexOf(firstArray[line]); 
 if (isMatched !== -1) 
 {
   var matchedValFromArray2 = secondArray[isMatched]
 };
}

If you want to compare 2D array (or two rows of a spreadsheet), you can use .join() method.

for(var i in firstArray)
{
  var duplicate = false;
  for(var j in secondArray)
  {
    if(firstArray[i].join() == secondArray[j].join())
    {
      var matchedValFromArray2 = firstArray[i];
      break;
    }
   }
 } 
like image 159
iJay Avatar answered Sep 08 '25 11:09

iJay