0

I have some code (at present just testing) that looks to match the values of one variable against another. It is within a For loop as it iterates through my Google Sheet. The loop is looking, bit the if statement doesn't seem to match items even when the values are the same. I have attached the following image to show both Image of code and Execution log and i have pasted the code itself below (as it is testing at present i am just watching what happens in the log). In the image you can see the first check should match but not the second, however both end up not matching. Can anyone help in identifying where i am going wrong?

function removeDuplicateEntry() {
  
  var app = SpreadsheetApp;
  // Get current active sheet
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();
  var lastRow = activeSheet.getLastRow();
  var nEntry = Sheets.Spreadsheets.Values.get('1do7V_jx6T9XDWl1gSMvCyiIJdaI39qyQpw28t3CnOqo', 'E'+lastRow+':I'+lastRow);
    
  for(var i=lastRow-1;i>1;i--){
    var oEntry = Sheets.Spreadsheets.Values.get('1do7V_jx6T9XDWl1gSMvCyiIJdaI39qyQpw28t3CnOqo', 'E'+i+':I'+i);
    if(oEntry.values === nEntry.values){ 
      Logger.log(nEntry.values);
      Logger.log(oEntry.values);
      Logger.log("MATCH");
      Logger.log(i);
      //activeSheet.deleteRow(i);
    } else {
      Logger.log(nEntry.values);
      Logger.log(oEntry.values);
      Logger.log("NO MATCH");
      Logger.log(i);
      
    }
  }
};

Kind reagrds,

John

1 Answers1

0

According to Umberto Raimondi's answer here.

Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable, works for null and undefined too).

To compare arrays, you can traverse both arrays and check if all the elements are the same or convert both array into string.

In your code, convert the array by using JSON.stringify():

JSON.stringify(oEntry.values) == oEntry.values(oEntry.values) 

I used convert to string method in my example below.

Example 1:

function myFunction() {
  var a = [[1, 2, 3 ,4]];
  var b = [[1, 2, 3 ,4]];
  if(JSON.stringify(a)==JSON.stringify(b)) 
    Logger.log("True"); 
  else
    Logger.log("False"); 
}

Output:

enter image description here

Example 2:

function myFunction() {
  var a = [[1, 2, 3 ,4]];
  var b = [[1, 2, 3 ,5]];
  if(JSON.stringify(a)==JSON.stringify(b)) 
    Logger.log("True"); 
  else
    Logger.log("False"); 
}

Output:

enter image description here

Further Reading:

See Tomáš Zato - Reinstate Monica answer on how to compare arrays.

Reference:

JSON.stringify()

Nikko J.
  • 5,319
  • 1
  • 5
  • 14