如何使用Google Scripts&Google Sheets执行笛卡尔连接? [英] How to perform Cartesian Join with Google Scripts & Google Sheets?

本文介绍了如何使用Google Scripts&Google Sheets执行笛卡尔连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了基本的两列笛卡尔联接的代码,但情况略有不同。

共有3个变量/列:颜色、颜色ID和项目(&;Item)。

我想要所有颜色和款式的组合。我希望使用Color变量将第三个变量Color ID附加到臀部。

这里是一个电子表格示例。列A-C是输入数据,列E-G是所需的输出(顺序不重要)。

https://docs.google.com/spreadsheets/d/1LgWttzY317T3N66Wk2JbDq8nETSGl1HCxY8u8i0jhl4/edit#gid=0

推荐答案

我相信您的目标如下。

  • 您希望使用Google Apps脚本实现以下转换。

    • 发件人

        Blue   74  Shirt
        Red    48  Pants
        Green  55  Shoes
                   Hat
                   Socks
                   Backpack
      
    •   Blue   74  Shirt
        Blue   74  Pants
        Blue   74  Shoes
        Blue   74  Hat
        Blue   74  Socks
        Blue   74  Backpack
        Red    48  Shirt
        Red    48  Pants
        Red    48  Shoes
        Red    48  Hat
        Red    48  Socks
        Red    48  Backpack
        Green  55  Shirt
        Green  55  Pants
        Green  55  Shoes
        Green  55  Hat
        Green  55  Socks
        Green  55  Backpack
      
  • 在示例电子表格中,Green, 55具有所有相同的值,即Backpack。但从您的示例模式来看,我认为您可能需要avove转换。

如果我的理解正确,我想提出以下流程。

  1. 将值从&Quot;A&Quot;列检索到&Quot;C&Quot;。
  2. 转置检索的值。
  3. 创建用于放入电子表格的数组。
  4. 放入值。

当上述流反映到脚本中时,将如下所示。

示例脚本:

请将以下脚本复制并粘贴到电子表格的脚本编辑器中,然后运行myFunction。这样,结果值就会放入";I2:k";列。

function myFunction() {
  const sheetName = "Sheet1";  // Please set the sheet name.

  // 1. Retrieve the values from the columns "A" to "C".
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const values = sheet.getRange("A2:C" + sheet.getLastRow()).getValues();

  // 2. Transpose the retrieved values.
  const [color, id, item] = values[0].map((_, i) => values.map(r => r[i]).filter(String));

  // 3. Create the array for putting to Spreadsheet.
  const res = color.flatMap((e, i) => item.map(g => [e, id[i], g]));

  // 4. Put the values.
  sheet.getRange(2, 9, res.length, res[0].length).setValues(res);
}

结果:

为示例电子表格运行上述脚本时,将获得以下结果。

引用:

这篇关于如何使用Google Scripts&Google Sheets执行笛卡尔连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆