Compare rows in google spreadsheets

I want to identify equal rows in two different worksheets on the same spreadsheet. I tried under the code, it does not work.

function getMyEqualRows()
{
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet1 = ss.getSheets()[0];
 var sheet2 = ss.getSheets()[1];

 var sheetOneValues = sheet1.getRange('A1:G20').getValues();
 var sheetTwoValues = sheet2.getRange('A1:G20').getValues();
 var equalRows = [];

 for (var i = 0; i <= sheetOneValues.length; i++) {    
  for(var j = 0; j <= sheetTwoValues.length; j++){
   if(sheetOneValues[i] == sheetTwoValues[j]) {
   equalRows.push(sheetOneValues[i]);
   }
  }
 return equalRows;
 }
}
+4
source share
1 answer

You cannot compare two arraysfor equality with ==. You can use a method instead .join(). It combines all the elements in these arrays into a string. This is a test string of arrays for equality. I am not sure if this is the best way.

function getMyEqualRows()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheets()[0];
  var sheet2 = ss.getSheets()[1];

  var sheetOneValues = sheet1.getRange('A1:G20').getValues();
  var sheetTwoValues = sheet2.getRange('A1:G20').getValues();

  var equalRows = [];

    for(var i in sheetOneValues)
    {
     var anEqualRow = false;
     for(var j in sheetTwoValues)
     {
      if(sheetOneValues[i].join() == sheetTwoValues[j].join()){
        anEqualRow = true;
      }
     }
     if(anEqualRow){
      equalRows.push(sheetOneValues[i]);
     }
   } 
  return equalRows;
}

Hope it works!

+2
source

Source: https://habr.com/ru/post/1625605/


All Articles