简体   繁体   English

Google Apps Script:如何通过从两列列表中读取来为给定值创建值数组?

[英]Google Apps Script: how to create an array of values for a given value by reading from a two column list?

I have a set of data in a Google spreadsheet in two columns.我在两列的 Google 电子表格中有一组数据。 One column is a list of article titles and the other is the ID of a hotel that is in that article.一列是文章标题列表,另一列是该文章中酒店的 ID。 Call it list1.称之为list1。

Example data 示例数据

I would like returned a new list with article titles in one column, and an array of the hotel IDs in that article in the other column.我想返回一个新列表,其中一列包含文章标题,另一列包含该文章中的酒店 ID 数组。 Call it list2.称之为list2。

Example data 示例数据

There are thousands of lines that this needs to be done for, and so my hope was to use Google Apps Script to help perform this task.这需要完成数千行,因此我希望使用 Google Apps Script 来帮助执行此任务。 My original thinking was to我原来的想法是

  1. Create column 1 of list2 which has the unique article titles (no script here, just the G-sheets =unique() formula.创建具有唯一文章标题的 list2 的第 1 列(此处没有脚本,只有 G-sheets =unique()公式。
  2. Iterate through the titles in list2, looking for a match in first column of the list1遍历 list2 中的标题,在 list1 的第一列中查找匹配项
  3. If there is a match:如果有匹配:
    • retrieve its corresponding value in column 2在第 2 列中检索其对应的值
    • push it to an empty array in column two of list2将其推送到 list2 的第二列中的空数组
    • move onto next row in list1移动到列表 1 中的下一行
  4. if no longer a match, loop back to step 2.如果不再匹配,则循环回到步骤 2。

I've written the following code.我已经编写了以下代码。 I am currently getting a type error ( TypeError: Cannot read property '0' of undefined (line 13, file "Code") ), however, I wanted to ask whether this is even a valid approach to the problem?我目前收到一个类型错误( TypeError: Cannot read property '0' of undefined (line 13, file "Code") ),但是,我想问一下这是否是解决问题的有效方法?

function getHotelIds() {
  
  var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
  var lastRow = outputSheet.getLastRow();
  var data = outputSheet.getRange(2,1,lastRow,2).getValues();
  
  var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
  var lastActiveRow = workingSheet.getLastRow();
  var itemIDS = [];
  
  for (var i=1; i<=data.length; i++) {
    var currentArticle = data[i][0];
    var lookupArticle = workingSheet[i][0];
    if (currentArticle === lookupArticle) {
      var tempValue = [workingSheet[i][1]];
      itemIDS.push(tempValue);
    }
  }
}

You got the idea right, but the logic needed some tweaking.你的想法是对的,但逻辑需要一些调整。 The "undefined" error is caused by the workingSheet[i][0] . “未定义”错误是由workingSheet[i][0] WorkingSheet is a Sheet object , not an array of data. WorkingSheet 是一个Sheet 对象,而不是一个数据数组。 Also, is not necessary to get the data from list2 (output), it is rather the opposite.此外,没有必要从list2 (输出)中获取数据,恰恰相反。 You have to get the data from the list1 (source) sheet instead, and iterate over it.您必须从list1 (源)表中获取数据,然后对其进行迭代。

I added a new variable, oldHotel , which will be used to compare each line with the current hotel.我添加了一个新变量oldHotel ,它将用于将每一行与当前酒店进行比较。 If it's different, it means we have reached a different Hotel and the data should be written in list2 .如果不同,说明我们到达了不同的Hotel,数据应该写在list2中

function getHotelIds() {

    var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
    var outLastRow = outputSheet.getLastRow();

    var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
    var lastActiveRow = workingSheet.getLastRow();
    var sourceValues = workingSheet.getRange("A2:B" + lastActiveRow).getValues();

    var itemIDS = [];
    var oldHotel = sourceValues[0][0]; //first hotel of the list

    for (var i = 0; i < sourceValues.length; i++) {

        if (sourceValues[i][0] == oldHotel) {

            itemIDS.push(sourceValues[i][1]);
            /*When we reach the end of the list, the oldHotel variable will never be different. So the next if condition is needed. Otherwise it wouldn't write down the last Hotel.
            */
            if (i == sourceValues.length - 1) {
                outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
                    [sourceValues[i][0], itemIDS.toString()]
                ]);
            }

        } else {

            outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
                [sourceValues[i - 1][0], itemIDS.toString()]
            ]);
            oldHotel = sourceValues[i][0]; //new Hotel will be compared
            outLastRow = outputSheet.getLastRow(); //lastrow has updated
            itemIDS = []; //clears the array to include the next codes
        }
    }
}

I also converted the itemIDS array to a String each time, so it's written down in a single cell without issues.我也每次都将itemIDS数组转换为 String,因此它可以毫无问题地记录在单个单元格中。

Make sure each column of the Sheet is set to "Plain text" from Format > Number > Plain Text确保从格式> 数字> 纯文本中将工作表的每一列设置为“纯文本”

References参考

Use a simple google sheets formula:使用一个简单的谷歌表格公式:

You can use a very simple formula to achieve your goal instead of using long and complicated scripts.您可以使用一个非常简单的公式来实现您的目标,而不是使用冗长而复杂的脚本。

Use =unique(list1!A2:A) in cell A2 of list2 sheet to get the unique hotels.list2表的单元格A2中使用=unique(list1!A2:A)来获取唯一的酒店。

and then use this formula to all the unique hotels by dragging it down in column B.然后将此公式用于所有独特的酒店,方法是将其拖到 B 列中。

=JOIN(",",filter(list1!B:B,list1!A:A=A2))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Apps Script:根据其他列的值在数组中创建一个新列 - Google Apps Script: Create a new column in array based on value of other columns 如何使用 Google Apps 脚本将值添加到带有 for 循环的二维数组 - How To Add values to two-dimensional array with for loops using Google Apps Script 如何使用来自不同一维数组的数据过滤二维数组 - Javascript/Google Apps 脚本? - How to filter a two dimensional array using data from a different one dimensional array - Javascript/Google Apps Script? 如何使用 Google Apps 脚本从 JSON 创建数组并将值导入到 Google 表格中的多行 - How to Create an Array From JSON and Import the Values to Multiple Rows in a Google Sheet Using Google Apps Scripts 根据列值搜索行,更改从输入表中的值找到的行的值 - Google Apps 脚本(表) - Search for Row based on Column Value, Change Values of Row Found from Values in Input sheet- Google Apps Script (Sheets) 使用 Google Apps 脚本从数组中获取最后一个值 - Get last value from an array using Google Apps Script 如何从文件创建给定值的数组? - How to create an array of given values from a file? Google Apps 脚本 - 将数据列转换为数组 - Google Apps Script - Converting column of data into an array 如何检查数组是否包含某些值 google Apps Script - How to check whether array includes certain value google Apps Script 比较Google Apps脚本中的数组值 - Comparing array values in Google Apps script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM