繁体   English   中英

Apps 脚本 - 比较两个数组中的字符串

[英]Apps Script - compare strings in two arrays

我被困在这段代码上。 我有一个带有两个选项卡的示例表 第一个选项卡是新项目。 一个新项目由两部分组成,一个属性代码(字符串)和一个项目 ID(数字)。 在另一个选项卡“位置”中有一堆空位置。 每个位置都有主要属性(字符串)和较长字符串中的一组次要属性代码。

我已将这两个范围分配给两个唯一的数组。

function matchcodes() {

var locss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Locations');
var lastlocRow = locss.getLastRow();
var newitems = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('New Items');
var lastNIRow = newitems.getLastRow();
var itemcodes = newitems.getRange("A1:B" + lastNIRow).getValues();
var locations = locationssheet.getRange("A2:D" + lastlocationRow).getValues();
Logger.log(itemcodes)
Logger.log(locations)}

我正在尝试做的是将itemcodes[i][0]locations[j][2]进行比较(将 item 属性与 location 主要属性匹配)。 如果字符串匹配,我想复制itemcodes[i][1] (ItemID) 并将其设置为locations[j][1]的值。 如果字符串不匹配,请检查locations[j][2]的下一次迭代。 如果在locations[j][2]中没有找到匹配的属性,我想看看它是否作为一个子字符串包含在locations[j][3]中(从顶部开始并遍历整个辅助属性列表. 如果子字符串代码包含在loactions[j][3]我想在第一个 IF 条件中采取相同的操作。

一旦匹配了一个新项目,循环就会中断,下一个项目可以位于itemcodes[i+1][0] 如果在主要或次要搜索中未找到匹配项,则还迭代到下一个新项目。

我正在努力编写条件语句来比较字符串中的字符串和子字符串。

//for (var i = 0; i < itemcodes.length; i++) {
   //for (var j = 0; j < locations.length; j++) {
    //if (itemcodes[i][0] == locations[j][2]) {
      // I want set the value of locations[j][1] with itemcodes[i][1] 
    }
     // if no match is found in entire [j][2] column, search for substring in locations[j][3] column
    //if item match is found, or no match is found in all of [j][2] or [j][3] break loop and iterate to [i+1][0] and start the next loop

输入(3 次迭代)结果

任何帮助将非常感激。 或者,如果你能指出我类似的线程。 (我没有成功找到类似的例子)提前谢谢!

尝试:

function matchCodes() {

  const newItems = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(`New Items`)
  const locations = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(`Locations`)

  const newItemsValues = newItems.getDataRange().getValues()
  const locationsValues = locations.getDataRange().offset(1, 0).getValues()

  newItemsValues.forEach(([attribute, id]) => {

    const primaryTarget = locationsValues.findIndex(row => row[2] === attribute && row[1] === ``)
    if (primaryTarget !== -1) return locationsValues[primaryTarget][1] = id

    const secondaryTarget = locationsValues.findIndex(row => row[3].includes(attribute) && row[1] === ``)
    if (secondaryTarget !== -1) return locationsValues[secondaryTarget][1] = id

  })

  locations.getDataRange().offset(1, 0).setValues(locationsValues)

}

学到更多:

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM