Compare sheet 1 to sheet 2 and output to sheet 3. Google sheets. JavaScript

纵然是瞬间 提交于 2020-04-18 00:52:38

问题


The following code works successfully to compare column A of sheet 2 with Column B of sheet 1, any matches will copy the entire row to sheet 3. However im needing a very slight change of this code that compares column A of sheet 2 to column N of sheet 1 instead of column B. Could someone help me with this code change? Here is the link to the previous post Java script optimization for a google apps script

 function copyRowtoSheet3() {
  var spreadsheetId = "1Aw11LiKzyezfrTQIuTsJPhUFtz8RPqLCc8FlIiy0ZlE";
  var ss = SpreadsheetApp.openById(spreadsheetId);
  var s1 = ss.getSheetByName('Sheet1');
  var s2 = ss.getSheetByName('Sheet2');
  // 1. Retrieve values from "Sheet1" and "Sheet2",
  var values1 = s1.getDataRange().getValues();
  var values2 = s2.getRange(1, 1, s2.getLastRow(), 1).getValues();

  // 2. Create an object using values2.
  var obj = values2.reduce((o, [e]) => {
    o[e] = null;
    return o;
  }, {});

  // 3. Create resultArray using values1 and obj.
  var resultArray = values1.filter(([,b]) => b in obj);

  // 4. Put resultArray to Sheet3.
  Sheets.Spreadsheets.Values.update({values: resultArray}, spreadsheetId, "Sheet3", {valueInputOption: "USER_ENTERED"});
}

What I have attempted is:

var resultArray = values1.filter(([,n]) => n in obj);

However that did not work. Any ideas?


回答1:


  • You want to retrieve the values of "Sheet1" and "Sheet2".
  • You want to compare the column "N" of "Sheet1" and the column "A" of "Sheet2". When the values of the column "N" of "Sheet1" and the column "A" of "Sheet2" are the same, you want to retrieve the row of "Sheet1" and put to "Sheet3".
  • You want to achieve this by modifying your script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification point:

  • var resultArray = values1.filter(([,b]) => b in obj); is modified. In your current script, the column "B" from [,b] is compared.

Modified script:

When your script is modified, please modify as follows.

From:
var resultArray = values1.filter(([,b]) => b in obj);
To:
var resultArray = values1.filter(b => b[13] in obj);

If I misunderstood your question and this was not the result you want, I apologize.



来源:https://stackoverflow.com/questions/60951952/compare-sheet-1-to-sheet-2-and-output-to-sheet-3-google-sheets-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!