我有一長串角色是從存盤為陣列中的字串的作業表范圍中獲得的,舉個例子,陣列看起來像這樣:
arr1 = ["football manager","hockey coach", "fb player","fb coach","footballer"];
我有另一個陣列,其中有一小部分標簽
arr2 = ["football","fb", "footballer","hockey","rugby"];
我正在嘗試將第一個陣列的角色與第二個陣列的標簽相匹配。
我一直試圖通過回圈并獲取匹配行的索引來做到這一點:
for(let i in arr1){
arr2.findIndex(s => s.indexOf(arr1[i]) >= 0);
}
但這僅適用于“足球運動員”,因為它是完全匹配的,我也需要對所有部分匹配進行分類。
uj5u.com熱心網友回復:
使用以下函式查找arr2與來自arr1.
按照代碼注釋進行詳細說明。
function matchTagIndexes()
{
// TODO replace with your values
arr1 = ["football manager","hockey coach", "fb player","fb coach","footballer"];
// TODO replace with your tags
arr2 = ["football","fb", "footballer","hockey","rugby"];
// for all tags create regex objects
// regex searches for any match that have `tag` surrounded with word (\b) boundaries
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet#boundary-type_assertions
const arr2Regexes = arr2.map(tag => new RegExp(`\\b${tag}\\b`, 'i'));
// loop arr1 values as val
arr1.map(val =>
// for each arr2 regex match val
arr2Regexes.forEach((regex, i) =>
// if it is matched, log value from arr1 array, matched tag name and tag's index in arr2 array
val.match(regex) && console.log(`"${val}" matches tag "${arr2[i]}" which has index ${i}`)
)
);
}
結果:
| 時間 | 狀態 | 資訊 |
|---|---|---|
| 晚上 8 點 46 分 35 秒 | 注意 | 執行開始 |
| 晚上 8 點 46 分 35 秒 | 資訊 | "football manager" 匹配索引為 0 的標簽 "football" |
| 晚上 8 點 46 分 35 秒 | 資訊 | “曲棍球教練”匹配索引為 3 的標簽“曲棍球” |
| 晚上 8 點 46 分 35 秒 | 資訊 | "fb player" 匹配索引為 1 的標簽 "fb" |
| 晚上 8 點 46 分 35 秒 | 資訊 | "fb coach" 匹配索引為 1 的標簽 "fb" |
| 晚上 8 點 46 分 35 秒 | 資訊 | "footballer" 匹配索引為 2 的標簽 "footballer" |
| 晚上 8 點 46 分 36 秒 | 注意 | 執行完成 |
參考:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet#boundary-type_assertions
uj5u.com熱心網友回復:
我懷疑某些文本可能有多個標簽(arr1)。這是獲取每個文本的標簽(索引)陣列的解決方案:
var texts = ['football manager','hockey coach', 'fb player','fb coach','footballer', 'none'];
var tags = ['football','fb', 'footballer','hockey','rugby', 'coach'];
// get all tags for all the texts
var list = [];
for (let tag of tags) {
var mask = RegExp('\\b' tag '\\b', 'i');
for (let text of texts) {
if (text.match(mask))
list.push( {'text': text, 'tag': tag, 'tag_index': tags.indexOf(tag)} );
}
}
console.log(list);
// group tags for the same texts
var text_and_tags = {};
for (let element of list) {
try { text_and_tags[element.text].push(element.tag_index) }
catch(e) { text_and_tags[element.text] = [element.tag_index] }
}
console.log(text_and_tags);
它將為您text_and_tags提供如下物件:
{
'football manager': [ 0 ],
'fb player': [ 1 ],
'fb coach': [ 1, 5 ],
'footballer': [ 2 ],
'hockey coach': [ 3, 5 ]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432779.html
標籤:javascript 数组 谷歌应用脚本 字符串匹配 指数
上一篇:谷歌表單預訂
下一篇:電子表格跳轉到當前日期問題
