![](/img/trans.png)
[英]How to Exact Match a list of words in a list of strings Google Apps Script
[英]How to filter array for only exact match in Google Apps Script/Javascript
我正在嘗試使用 Google Apps 腳本僅過濾完全匹配。 我見過類似的問題,但我似乎無法將它們應用於我的情況。
在一張紙上,我有一個信息表,其中 A 列中的項目名稱,B 列中的“成分”和 C 列中的“數量”。 A 列包含名為 Test 和 Test 2 的項目。當我過濾 Test 2 時,我得到了 Test 和 Test 2 的結果。這是我正在使用的代碼:
var costSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Cost');
var ingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Recipe Ingredient');
// Create list of items to filter from the full list
var rows = costSheet.getLastRow();
var itemList = costSheet.getRange(2, 1, rows - 1).getValues();
// Convert itemList to array to be used in filter
itemList = itemList.join();
// Get full non-filtered data
var fullList = ingSheet.getRange('A2:C514').getValues();
// Apply filter criteria
function checkMatch(item) {
return itemList.indexOf(item[0]) != -1;
}
filterList = fullList.filter(checkMatch);
// Clear target location, then place filtered data
costSheet.getRange('C2:E514').clearContent();
costSheet.getRange(2, 3, filterList.length, 3).setValues(filterList);
我從所有三列中獲得多個項目的准確結果沒有任何問題,我遇到的唯一問題是當我嘗試過濾以完整列表中另一個項目的名稱開頭的項目時(例如過濾測試 2當我希望它只返回測試 2 時,返回測試和測試 2)。
我是使用 Google Apps Script/Javascript 的新手,因此是“業余”編碼。
你很親近!
該問題與此行有關:
itemList = itemList.join();
假設itemList = [["Test 2"],["Test 3"]]
作為getValues()
方法的結果。
如果您應用連接,則將上述數組轉換為以下string
:
Test 1,Test 2
因此itemList.indexOf("Test")
將返回0
這意味着您的過濾器 function 將評估為true
,但您不希望這樣,因為Test
不是您的數組的一部分。 您錯誤地使用了strings
的indexOf方法,而不是arrays
的indexOf方法。
話雖如此,您的目標是使用arrays
的indexOf方法。 為此, itemList
需要是一個數組而不是字符串。
要將二維數組[["Test 2"],["Test 3"]]
轉換為一維數組[Test 1, Test 2]
您可以使用flat 。
改變:
itemList = itemList.join();
至:
itemList = itemList.flat();
加倍努力,您可以縮短代碼並使其更現代JavaScript
像這樣:
function shorterFunction(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const costSheet = ss.getSheetByName('Cost');
const ingSheet = ss.getSheetByName('Recipe Ingredient');
const itemList = costSheet.getRange(2, 1, costSheet.getLastRow() - 1).getValues().flat();
const fullList = ingSheet.getRange('A2:C514').getValues();
const filterList = fullList.filter(r=>itemList.includes(r[0]))
costSheet.getRange('C2:E514').clearContent();
costSheet.getRange(2, 3, filterList.length, 3).setValues(filterList);
}
在此解決方案中,我使用了箭頭 function並包含.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.