Saurabh Garg Saurabh Garg - 8 days ago 4
Javascript Question

Compare the two array and set the value to True if value found in another array

I have two arrays
A = [1,5,9,12,14] and B = [16,4,8,12]
both the arrays have the different length. I want to compare the array A with B. If the value of array A is available in B then don't do anything else add it to sheet.
Below is my code for same but I am not getting desired output.
can anybody help me on the same?

function updateTicketsAreNotInDeploymentDoc() {
var A = getJiraNoFromJira();
var B = getJiraNoFromDoc();
for(var i = 0; i<A.length; i++) {
var data = new Array();
for(var j=0; j<B.length; j++) {
if(A[i] == B[j]) {
Logger.log("found="+A[i]);
}
}
data.push(A[i]);
}

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName(RESULTANT_DEPLOYMENT_SHEET);
sheet.appendRow(data);

}

Answer

The Sheet.appendRow() method only accept mono dimensionnal array, cause it's only add one row after the sheet. You must go through your list to append the data. As say on the documentation:

Appends a row to the spreadsheet. This operation is atomic; it prevents issues where a user asks for the last row, and then writes to that row, and an intervening mutation occurs between getting the last row and writing to it.

Here is a sample of code:

Edit: As @charlietfl point it, there's is other problem before: you instanciate your data array each time you loop on your A array.

The code as being modify to correct this.

function updateTicketsAreNotInDeploymentDoc() {
  var A = getJiraNoFromJira();
  var B = getJiraNoFromDoc();
  var data = new Array();
  for(var i = 0; i<A.length; i++) {
    var Found = false;
    for(var j=0; j<B.length; j++) {
      if(A[i] == B[j]) {
        Logger.log("found="+A[i]); 
        Found = true;
      }
    } 
    if(Found == false){
      data.push(A[i]);
    }
  }  

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(RESULTANT_DEPLOYMENT_SHEET);

  for(var k = 0; k<data.length; k++){
    sheet.appendRow([data[k]]);
  }
}