compare rows on google spreadsheets

2019-06-27 11:37发布

问题:

I want to identify equal rows in two different sheets on same spreadsheet. I tried below code, it doesn't 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;
 }
}

回答1:

You can't compare two arrays for equality with ==. Instead you can use .join() method. It concatenates all elements in these arrays to a string. This check string arrays for equality. I'm 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 this would work!